Wed May 5 15:18:34 2010

Asterisk developer's documentation


chan_sip.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*!
00020  * \file
00021  * \brief Implementation of Session Initiation Protocol
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * See Also:
00026  * \arg \ref AstCREDITS
00027  *
00028  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
00029  * Configuration file \link Config_sip sip.conf \endlink
00030  *
00031  * ********** IMPORTANT *
00032  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
00033  * settings, dialplan commands and dialplans apps/functions
00034  * See \ref sip_tcp_tls
00035  * 
00036  *
00037  * ******** General TODO:s
00038  * \todo Better support of forking
00039  * \todo VIA branch tag transaction checking
00040  * \todo Transaction support
00041  * 
00042  * ******** Wishlist: Improvements
00043  * - Support of SIP domains for devices, so that we match on username@domain in the From: header
00044  * - Connect registrations with a specific device on the incoming call. It's not done
00045  *   automatically in Asterisk
00046  *
00047  * \ingroup channel_drivers
00048  *
00049  * \par Overview of the handling of SIP sessions
00050  * The SIP channel handles several types of SIP sessions, or dialogs,
00051  * not all of them being "telephone calls".
00052  * - Incoming calls that will be sent to the PBX core
00053  * - Outgoing calls, generated by the PBX
00054  * - SIP subscriptions and notifications of states and voicemail messages
00055  * - SIP registrations, both inbound and outbound
00056  * - SIP peer management (peerpoke, OPTIONS)
00057  * - SIP text messages
00058  *
00059  * In the SIP channel, there's a list of active SIP dialogs, which includes
00060  * all of these when they are active. "sip show channels" in the CLI will
00061  * show most of these, excluding subscriptions which are shown by
00062  * "sip show subscriptions"
00063  *
00064  * \par incoming packets
00065  * Incoming packets are received in the monitoring thread, then handled by
00066  * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
00067  * sipsock_read() function parses the packet and matches an existing
00068  * dialog or starts a new SIP dialog.
00069  * 
00070  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
00071  * If it is a response to an outbound request, the packet is sent to handle_response().
00072  * If it is a request, handle_incoming() sends it to one of a list of functions
00073  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
00074  * sipsock_read locks the ast_channel if it exists (an active call) and
00075  * unlocks it after we have processed the SIP message.
00076  *
00077  * A new INVITE is sent to handle_request_invite(), that will end up
00078  * starting a new channel in the PBX, the new channel after that executing
00079  * in a separate channel thread. This is an incoming "call".
00080  * When the call is answered, either by a bridged channel or the PBX itself
00081  * the sip_answer() function is called.
00082  *
00083  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
00084  * in rtp.c 
00085  * 
00086  * \par Outbound calls
00087  * Outbound calls are set up by the PBX through the sip_request_call()
00088  * function. After that, they are activated by sip_call().
00089  * 
00090  * \par Hanging up
00091  * The PBX issues a hangup on both incoming and outgoing calls through
00092  * the sip_hangup() function
00093  */
00094 
00095 /*!  
00096  * \page sip_tcp_tls SIP TCP and TLS support
00097  * 
00098  * \par tcpfixes TCP implementation changes needed
00099  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
00100  * \todo Save TCP/TLS sessions in registry
00101  * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
00102  * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
00103  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
00104  *     The tcpbindaddr config option should only be used to open ADDITIONAL ports
00105  *     So we should propably go back to
00106  *    bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
00107  *          if tlsenable=yes, open TLS port (provided we also have cert)
00108  *    tcpbindaddr = extra address for additional TCP connections
00109  *    tlsbindaddr = extra address for additional TCP/TLS connections
00110  *    udpbindaddr = extra address for additional UDP connections
00111  *       These three options should take multiple IP/port pairs
00112  * Note: Since opening additional listen sockets is a *new* feature we do not have today
00113  *    the XXXbindaddr options needs to be disabled until we have support for it
00114  *    
00115  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
00116  *    thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
00117  * even if udp is the configured first transport.
00118  * 
00119  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
00120  *       specially to communication with other peers (proxies).
00121  * \todo We need to test TCP sessions with SIP proxies and in regards
00122  *       to the SIP outbound specs.
00123  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
00124  *
00125  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
00126  *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
00127  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
00128  *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
00129  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
00130  *  also considering outbound proxy options.
00131  *    First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
00132  *    Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
00133  * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
00134  * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
00135  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
00136  * devices directly from the dialplan. UDP is only a fallback if no other method works,
00137  * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
00138  *    MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
00139  *
00140  * When dialling unconfigured peers (with no port number)  or devices in external domains
00141  * NAPTR records MUST be consulted to find configured transport. If they are not found,
00142  * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
00143  * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
00144  * \note this only applies if there's no outbound proxy configured for the session. If an outbound
00145  * proxy is configured, these procedures might apply for locating the proxy and determining
00146  * the transport to use for communication with the proxy.
00147  * \par Other bugs to fix ----
00148  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
00149  * - sets TLS port as default for all TCP connections, unless other port is given in contact.
00150  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
00151  * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is 
00152  *   a bad guess.
00153  *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
00154  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
00155  * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
00156  *   we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
00157  *   fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
00158  *   channel variable in the dialplan.
00159  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
00160  * - As above, if we have a SIPS: uri in the refer-to header
00161  *    - Does not check transport in refer_to uri.
00162  */
00163 
00164 /*** MODULEINFO
00165         <depend>chan_local</depend>
00166  ***/
00167 
00168 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00169 
00170    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00171    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00172    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00173    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00174    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00175    that do not support Session-Timers).
00176 
00177    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00178    per-peer settings override the global settings. The following new parameters have been
00179    added to the sip.conf file.
00180       session-timers=["accept", "originate", "refuse"]
00181       session-expires=[integer]
00182       session-minse=[integer]
00183       session-refresher=["uas", "uac"]
00184 
00185    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00186    Asterisk. The Asterisk can be configured in one of the following three modes:
00187 
00188    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00189       made by remote end-points. A remote end-point can request Asterisk to engage
00190       session-timers by either sending it an INVITE request with a "Supported: timer"
00191       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00192       Session-Expires: header in it. In this mode, the Asterisk server does not 
00193       request session-timers from remote end-points. This is the default mode.
00194    2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
00195       end-points to activate session-timers in addition to honoring such requests
00196       made by the remote end-pints. In order to get as much protection as possible
00197       against hanging SIP channels due to network or end-point failures, Asterisk
00198       resends periodic re-INVITEs even if a remote end-point does not support
00199       the session-timers feature.
00200    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00201       timers for inbound or outbound requests. If a remote end-point requests
00202       session-timers in a dialog, then Asterisk ignores that request unless it's
00203       noted as a requirement (Require: header), in which case the INVITE is 
00204       rejected with a 420 Bad Extension response.
00205 
00206 */
00207 
00208 #include "asterisk.h"
00209 
00210 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 250253 $")
00211 
00212 #include <ctype.h>
00213 #include <sys/ioctl.h>
00214 #include <fcntl.h>
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <time.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 
00223 #include "asterisk/lock.h"
00224 #include "asterisk/channel.h"
00225 #include "asterisk/config.h"
00226 #include "asterisk/module.h"
00227 #include "asterisk/pbx.h"
00228 #include "asterisk/sched.h"
00229 #include "asterisk/io.h"
00230 #include "asterisk/rtp.h"
00231 #include "asterisk/udptl.h"
00232 #include "asterisk/acl.h"
00233 #include "asterisk/manager.h"
00234 #include "asterisk/callerid.h"
00235 #include "asterisk/cli.h"
00236 #include "asterisk/app.h"
00237 #include "asterisk/musiconhold.h"
00238 #include "asterisk/dsp.h"
00239 #include "asterisk/features.h"
00240 #include "asterisk/srv.h"
00241 #include "asterisk/astdb.h"
00242 #include "asterisk/causes.h"
00243 #include "asterisk/utils.h"
00244 #include "asterisk/file.h"
00245 #include "asterisk/astobj.h"
00246 /* 
00247    Uncomment the define below,  if you are having refcount related memory leaks.
00248    With this uncommented, this module will generate a file, /tmp/refs, which contains
00249    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00250    be modified to ao2_t_* calls, and include a tag describing what is happening with 
00251    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00252    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00253    balanced, along with the complete history for that object.
00254    In normal operation, the macros defined will throw away the tags, so they do not 
00255    affect the speed of the program at all. They can be considered to be documentation.
00256 */
00257 /* #define  REF_DEBUG 1 */
00258 #include "asterisk/astobj2.h"
00259 #include "asterisk/dnsmgr.h"
00260 #include "asterisk/devicestate.h"
00261 #include "asterisk/linkedlists.h"
00262 #include "asterisk/stringfields.h"
00263 #include "asterisk/monitor.h"
00264 #include "asterisk/netsock.h"
00265 #include "asterisk/localtime.h"
00266 #include "asterisk/abstract_jb.h"
00267 #include "asterisk/threadstorage.h"
00268 #include "asterisk/translate.h"
00269 #include "asterisk/ast_version.h"
00270 #include "asterisk/event.h"
00271 #include "asterisk/tcptls.h"
00272 #include "asterisk/strings.h"
00273 
00274 /*** DOCUMENTATION
00275    <application name="SIPDtmfMode" language="en_US">
00276       <synopsis>
00277          Change the dtmfmode for a SIP call.
00278       </synopsis>
00279       <syntax>
00280          <parameter name="mode" required="true">
00281             <enumlist>
00282                <enum name="inband" />
00283                <enum name="info" />
00284                <enum name="rfc2833" />
00285             </enumlist>
00286          </parameter>
00287       </syntax>
00288       <description>
00289          <para>Changes the dtmfmode for a SIP call.</para>
00290       </description>
00291    </application>
00292    <application name="SIPAddHeader" language="en_US">
00293       <synopsis>
00294          Add a SIP header to the outbound call.
00295       </synopsis>
00296       <syntax argsep=":">
00297          <parameter name="Header" required="true" />
00298          <parameter name="Content" required="true" />
00299       </syntax>
00300       <description>
00301          <para>Adds a header to a SIP call placed with DIAL.</para>
00302          <para>Remember to use the X-header if you are adding non-standard SIP
00303          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00304          Adding the wrong headers may jeopardize the SIP dialog.</para>
00305          <para>Always returns <literal>0</literal>.</para>
00306       </description>
00307    </application>
00308    <application name="SIPRemoveHeader" language="en_US">
00309       <synopsis>
00310          Remove SIP headers previously added with SIPAddHeader
00311       </synopsis>
00312       <syntax>
00313          <parameter name="Header" required="false" />
00314       </syntax>
00315       <description>
00316          <para>SIPRemoveHeader() allows you to remove headers which were previously 
00317          added with SIPAddHeader(). If no parameter is supplied, all previously added 
00318          headers will be removed. If a parameter is supplied, only the matching headers 
00319          will be removed.</para>
00320          <para>For example you have added these 2 headers:</para>
00321          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00322          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00323          <para></para>
00324          <para>// remove all headers</para>
00325          <para>SIPRemoveHeader();</para>
00326          <para>// remove all P- headers</para>
00327          <para>SIPRemoveHeader(P-);</para>
00328          <para>// remove only the PAI header (note the : at the end)</para>
00329          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00330          <para></para>
00331          <para>Always returns <literal>0</literal>.</para>
00332       </description>
00333    </application>
00334    <function name="SIP_HEADER" language="en_US">
00335       <synopsis>
00336          Gets the specified SIP header.
00337       </synopsis>
00338       <syntax>
00339          <parameter name="name" required="true" />
00340          <parameter name="number">
00341             <para>If not specified, defaults to <literal>1</literal>.</para>
00342          </parameter>
00343       </syntax>
00344       <description>
00345          <para>Since there are several headers (such as Via) which can occur multiple
00346          times, SIP_HEADER takes an optional second argument to specify which header with
00347          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00348       </description>
00349    </function>
00350    <function name="SIPPEER" language="en_US">
00351       <synopsis>
00352          Gets SIP peer information.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="peername" required="true" />
00356          <parameter name="item">
00357             <enumlist>
00358                <enum name="ip">
00359                   <para>(default) The ip address.</para>
00360                </enum>
00361                <enum name="port">
00362                   <para>The port number.</para>
00363                </enum>
00364                <enum name="mailbox">
00365                   <para>The configured mailbox.</para>
00366                </enum>
00367                <enum name="context">
00368                   <para>The configured context.</para>
00369                </enum>
00370                <enum name="expire">
00371                   <para>The epoch time of the next expire.</para>
00372                </enum>
00373                <enum name="dynamic">
00374                   <para>Is it dynamic? (yes/no).</para>
00375                </enum>
00376                <enum name="callerid_name">
00377                   <para>The configured Caller ID name.</para>
00378                </enum>
00379                <enum name="callerid_num">
00380                   <para>The configured Caller ID number.</para>
00381                </enum>
00382                <enum name="callgroup">
00383                   <para>The configured Callgroup.</para>
00384                </enum>
00385                <enum name="pickupgroup">
00386                   <para>The configured Pickupgroup.</para>
00387                </enum>
00388                <enum name="codecs">
00389                   <para>The configured codecs.</para>
00390                </enum>
00391                <enum name="status">
00392                   <para>Status (if qualify=yes).</para>
00393                </enum>
00394                <enum name="regexten">
00395                   <para>Registration extension.</para>
00396                </enum>
00397                <enum name="limit">
00398                   <para>Call limit (call-limit).</para>
00399                </enum>
00400                <enum name="busylevel">
00401                   <para>Configured call level for signalling busy.</para>
00402                </enum>
00403                <enum name="curcalls">
00404                   <para>Current amount of calls. Only available if call-limit is set.</para>
00405                </enum>
00406                <enum name="language">
00407                   <para>Default language for peer.</para>
00408                </enum>
00409                <enum name="accountcode">
00410                   <para>Account code for this peer.</para>
00411                </enum>
00412                <enum name="useragent">
00413                   <para>Current user agent id for peer.</para>
00414                </enum>
00415                <enum name="chanvar[name]">
00416                   <para>A channel variable configured with setvar for this peer.</para>
00417                </enum>
00418                <enum name="codec[x]">
00419                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00420                </enum>
00421             </enumlist>
00422          </parameter>
00423       </syntax>
00424       <description />
00425    </function>
00426    <function name="SIPCHANINFO" language="en_US">
00427       <synopsis>
00428          Gets the specified SIP parameter from the current channel.
00429       </synopsis>
00430       <syntax>
00431          <parameter name="item" required="true">
00432             <enumlist>
00433                <enum name="peerip">
00434                   <para>The IP address of the peer.</para>
00435                </enum>
00436                <enum name="recvip">
00437                   <para>The source IP address of the peer.</para>
00438                </enum>
00439                <enum name="from">
00440                   <para>The URI from the <literal>From:</literal> header.</para>
00441                </enum>
00442                <enum name="uri">
00443                   <para>The URI from the <literal>Contact:</literal> header.</para>
00444                </enum>
00445                <enum name="useragent">
00446                   <para>The useragent.</para>
00447                </enum>
00448                <enum name="peername">
00449                   <para>The name of the peer.</para>
00450                </enum>
00451                <enum name="t38passthrough">
00452                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00453                   otherwise <literal>0</literal>.</para>
00454                </enum>
00455             </enumlist>
00456          </parameter>
00457       </syntax>
00458       <description />
00459    </function>
00460    <function name="CHECKSIPDOMAIN" language="en_US">
00461       <synopsis>
00462          Checks if domain is a local domain.
00463       </synopsis>
00464       <syntax>
00465          <parameter name="domain" required="true" />
00466       </syntax>
00467       <description>
00468          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00469          as a local SIP domain that this Asterisk server is configured to handle.
00470          Returns the domain name if it is locally handled, otherwise an empty string.
00471          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00472       </description>
00473    </function>
00474  ***/
00475 
00476 #ifndef FALSE
00477 #define FALSE    0
00478 #endif
00479 
00480 #ifndef TRUE
00481 #define TRUE     1
00482 #endif
00483 
00484 /* Arguments for find_peer */
00485 #define FINDUSERS (1 << 0)
00486 #define FINDPEERS (1 << 1)
00487 #define FINDALLDEVICES (FINDUSERS | FINDPEERS)
00488 
00489 #define  SIPBUFSIZE     512      /*!< Buffer size for many operations */
00490 
00491 #define XMIT_ERROR      -2
00492 
00493 #define SIP_RESERVED ";/?:@&=+$,# "    /*!< Reserved characters in the username part of the URI */
00494 
00495 /* #define VOCAL_DATA_HACK */
00496 
00497 #define DEFAULT_DEFAULT_EXPIRY  120
00498 #define DEFAULT_MIN_EXPIRY      60
00499 #define DEFAULT_MAX_EXPIRY      3600
00500 #define DEFAULT_MWI_EXPIRY      3600
00501 #define DEFAULT_REGISTRATION_TIMEOUT 20
00502 #define DEFAULT_MAX_FORWARDS    "70"
00503 
00504 /* guard limit must be larger than guard secs */
00505 /* guard min must be < 1000, and should be >= 250 */
00506 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
00507 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
00508                                                     EXPIRY_GUARD_SECS */
00509 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
00510                                                    GUARD_PCT turns out to be lower than this, it 
00511                                                    will use this time instead.
00512                                                    This is in milliseconds. */
00513 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
00514                                                     below EXPIRY_GUARD_LIMIT */
00515 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
00516 
00517 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00518 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00519 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00520 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00521 
00522 #define DEFAULT_QUALIFY_GAP   100
00523 #define DEFAULT_QUALIFY_PEERS 1
00524 
00525 
00526 #define CALLERID_UNKNOWN             "Anonymous"
00527 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00528 
00529 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00530 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00531 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00532 
00533 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00534 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00535 #define DEFAULT_TIMER_T1                 500              /*!< SIP timer T1 (according to RFC 3261) */
00536 #define SIP_TRANS_TIMEOUT            64 * DEFAULT_TIMER_T1 /*!< SIP request timeout (rfc 3261) 64*T1 
00537                                                       \todo Use known T1 for timeout (peerpoke)
00538                                                       */
00539 #define DEFAULT_TRANS_TIMEOUT        -1               /*!< Use default SIP transaction timeout */
00540 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00541 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00542 
00543 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00544 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
00545 #define SIP_MIN_PACKET               4096             /*!< Initialize size of memory to allocate for packets */
00546 #define MAX_HISTORY_ENTRIES        50                /*!< Max entires in the history list for a sip_pvt */
00547 
00548 #define INITIAL_CSEQ                 101              /*!< Our initial sip sequence number */
00549 
00550 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00551 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00552 
00553 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00554 
00555 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00556 static struct ast_jb_conf default_jbconf =
00557 {
00558    .flags = 0,
00559    .max_size = -1,
00560    .resync_threshold = -1,
00561    .impl = "",
00562    .target_extra = -1,
00563 };
00564 static struct ast_jb_conf global_jbconf;     /*!< Global jitterbuffer configuration */
00565 
00566 static const char config[] = "sip.conf";     /*!< Main configuration file */
00567 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00568 
00569 #define RTP    1
00570 #define NO_RTP 0
00571 
00572 /*! \brief Authorization scheme for call transfers 
00573 
00574 \note Not a bitfield flag, since there are plans for other modes,
00575    like "only allow transfers for authenticated devices" */
00576 enum transfermodes {
00577    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00578    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00579 };
00580 
00581 
00582 /*! \brief The result of a lot of functions */
00583 enum sip_result {
00584    AST_SUCCESS = 0,     /*!< FALSE means success, funny enough */
00585    AST_FAILURE = -1,    /*!< Failure code */
00586 };
00587 
00588 /*! \brief States for the INVITE transaction, not the dialog 
00589    \note this is for the INVITE that sets up the dialog
00590 */
00591 enum invitestates {
00592    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00593    INV_CALLING = 1,  /*!< Invite sent, no answer */
00594    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00595    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00596    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00597    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00598    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00599                  The only way out of this is a BYE from one side */
00600    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00601 };
00602 
00603 /*! \brief Readable descriptions of device states.
00604        \note Should be aligned to above table as index */
00605 static const struct invstate2stringtable {
00606    const enum invitestates state;
00607    const char *desc;
00608 } invitestate2string[] = {
00609    {INV_NONE,              "None"  },
00610    {INV_CALLING,           "Calling (Trying)"},
00611    {INV_PROCEEDING,        "Proceeding "},
00612    {INV_EARLY_MEDIA,       "Early media"},
00613    {INV_COMPLETED,         "Completed (done)"},
00614    {INV_CONFIRMED,         "Confirmed (up)"},
00615    {INV_TERMINATED,        "Done"},
00616    {INV_CANCELLED,         "Cancelled"}
00617 };
00618 
00619 /*! \brief When sending a SIP message, we can send with a few options, depending on
00620    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00621    where the original response would be sent RELIABLE in an INVITE transaction */
00622 enum xmittype {
00623    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00624                                               If it fails, it's critical and will cause a teardown of the session */
00625    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00626    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00627 };
00628 
00629 /*! \brief Results from the parse_register() function */
00630 enum parse_register_result {
00631    PARSE_REGISTER_DENIED,
00632    PARSE_REGISTER_FAILED,
00633    PARSE_REGISTER_UPDATE,
00634    PARSE_REGISTER_QUERY,
00635 };
00636 
00637 /*! \brief Type of subscription, based on the packages we do support, see \ref subscription_types */
00638 enum subscriptiontype { 
00639    NONE = 0,
00640    XPIDF_XML,
00641    DIALOG_INFO_XML,
00642    CPIM_PIDF_XML,
00643    PIDF_XML,
00644    MWI_NOTIFICATION
00645 };
00646 
00647 /*! \brief Subscription types that we support. We support
00648    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00649    - SIMPLE presence used for device status
00650    - Voicemail notification subscriptions
00651 */
00652 static const struct cfsubscription_types {
00653    enum subscriptiontype type;
00654    const char * const event;
00655    const char * const mediatype;
00656    const char * const text;
00657 } subscription_types[] = {
00658    { NONE,        "-",        "unknown",               "unknown" },
00659    /* RFC 4235: SIP Dialog event package */
00660    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00661    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00662    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00663    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00664    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00665 };
00666 
00667 
00668 /*! \brief Authentication types - proxy or www authentication 
00669    \note Endpoints, like Asterisk, should always use WWW authentication to
00670    allow multiple authentications in the same call - to the proxy and
00671    to the end point.
00672 */
00673 enum sip_auth_type {
00674    PROXY_AUTH = 407,
00675    WWW_AUTH = 401,
00676 };
00677 
00678 /*! \brief Authentication result from check_auth* functions */
00679 enum check_auth_result {
00680    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00681       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00682 
00683    AUTH_SUCCESSFUL = 0,
00684    AUTH_CHALLENGE_SENT = 1,
00685    AUTH_SECRET_FAILED = -1,
00686    AUTH_USERNAME_MISMATCH = -2,
00687    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00688    AUTH_FAKE_AUTH = -4,
00689    AUTH_UNKNOWN_DOMAIN = -5,
00690    AUTH_PEER_NOT_DYNAMIC = -6,
00691    AUTH_ACL_FAILED = -7,
00692    AUTH_BAD_TRANSPORT = -8,
00693 };
00694 
00695 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00696 enum sipregistrystate {
00697    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00698        *  \note Initial state. We should have a timeout scheduled for the initial
00699        * (or next) registration transmission, calling sip_reregister
00700        */
00701 
00702    REG_STATE_REGSENT,   /*!< Registration request sent 
00703        * \note sent initial request, waiting for an ack or a timeout to
00704        * retransmit the initial request.
00705       */
00706 
00707    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00708        * \note entered after transmit_register with auth info,
00709        * waiting for an ack.
00710        */
00711 
00712    REG_STATE_REGISTERED,   /*!< Registered and done */
00713 
00714    REG_STATE_REJECTED,  /*!< Registration rejected *
00715        * \note only used when the remote party has an expire larger than
00716        * our max-expire. This is a final state from which we do not
00717        * recover (not sure how correctly).
00718        */
00719 
00720    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00721       * \note XXX unused */
00722 
00723    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00724        * \note fatal - no chance to proceed */
00725 
00726    REG_STATE_FAILED, /*!< Registration failed after several tries
00727        * \note fatal - no chance to proceed */
00728 };
00729 
00730 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00731 enum st_mode {
00732         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00733         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00734         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00735         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00736 };
00737 
00738 /*! \brief The entity playing the refresher role for Session-Timers */
00739 enum st_refresher {
00740         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00741         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00742         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00743 };
00744 
00745 /*! \brief Define some implemented SIP transports 
00746    \note Asterisk does not support SCTP or UDP/DTLS 
00747 */
00748 enum sip_transport {
00749    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00750    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00751    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00752 };
00753 
00754 /*! \brief definition of a sip proxy server
00755  *
00756  * For outbound proxies, a sip_peer will contain a reference to a 
00757  * dynamically allocated instance of a sip_proxy. A sip_pvt may also
00758  * contain a reference to a peer's outboundproxy, or it may contain
00759  * a reference to the sip_cfg.outboundproxy.
00760  */
00761 struct sip_proxy {
00762    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00763    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00764    time_t last_dnsupdate;          /*!< When this was resolved */
00765    enum sip_transport transport; 
00766    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00767    /* Room for a SRV record chain based on the name */
00768 };
00769 
00770 /*! \brief argument for the 'show channels|subscriptions' callback. */
00771 struct __show_chan_arg { 
00772    int fd;
00773    int subscriptions;
00774    int numchans;   /* return value */
00775 };
00776 
00777 
00778 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00779 enum can_create_dialog {
00780    CAN_NOT_CREATE_DIALOG,
00781    CAN_CREATE_DIALOG,
00782    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00783 };
00784 
00785 /*! \brief SIP Request methods known by Asterisk 
00786 
00787    \note Do _NOT_ make any changes to this enum, or the array following it;
00788    if you think you are doing the right thing, you are probably
00789    not doing the right thing. If you think there are changes
00790    needed, get someone else to review them first _before_
00791    submitting a patch. If these two lists do not match properly
00792    bad things will happen.
00793 */
00794 
00795 enum sipmethod {
00796    SIP_UNKNOWN,      /*!< Unknown response */
00797    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00798    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00799    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00800    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00801    SIP_INVITE,    /*!< Set up a session */
00802    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00803    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00804    SIP_BYE,    /*!< End of a session */
00805    SIP_REFER,     /*!< Refer to another URI (transfer) */
00806    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00807    SIP_MESSAGE,      /*!< Text messaging */
00808    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00809    SIP_INFO,      /*!< Information updates during a session */
00810    SIP_CANCEL,    /*!< Cancel an INVITE */
00811    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00812    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00813 };
00814 
00815 /*! \brief Settings for the 'notifycid' option, see sip.conf.sample for details. */
00816 enum notifycid_setting {
00817    DISABLED       = 0,
00818    ENABLED        = 1,
00819    IGNORE_CONTEXT = 2,
00820 };
00821 
00822 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00823    structure and then route the messages according to the type.
00824 
00825       \note Note that sip_methods[i].id == i must hold or the code breaks */
00826 static const struct  cfsip_methods { 
00827    enum sipmethod id;
00828    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00829    char * const text;
00830    enum can_create_dialog can_create;
00831 } sip_methods[] = {
00832    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00833    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00834    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00835    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00836    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00837    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00838    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00839    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00840    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00841    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00842    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00843    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00844    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00845    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00846    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00847    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00848    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00849 };
00850 
00851 static unsigned int chan_idx;
00852 
00853 /*!  Define SIP option tags, used in Require: and Supported: headers 
00854    We need to be aware of these properties in the phones to use 
00855    the replace: header. We should not do that without knowing
00856    that the other end supports it... 
00857    This is nothing we can configure, we learn by the dialog
00858    Supported: header on the REGISTER (peer) or the INVITE
00859    (other devices)
00860    We are not using many of these today, but will in the future.
00861    This is documented in RFC 3261
00862 */
00863 #define SUPPORTED    1
00864 #define NOT_SUPPORTED      0
00865 
00866 /* SIP options */
00867 #define SIP_OPT_REPLACES   (1 << 0)
00868 #define SIP_OPT_100REL     (1 << 1)
00869 #define SIP_OPT_TIMER      (1 << 2)
00870 #define SIP_OPT_EARLY_SESSION (1 << 3)
00871 #define SIP_OPT_JOIN    (1 << 4)
00872 #define SIP_OPT_PATH    (1 << 5)
00873 #define SIP_OPT_PREF    (1 << 6)
00874 #define SIP_OPT_PRECONDITION  (1 << 7)
00875 #define SIP_OPT_PRIVACY    (1 << 8)
00876 #define SIP_OPT_SDP_ANAT   (1 << 9)
00877 #define SIP_OPT_SEC_AGREE  (1 << 10)
00878 #define SIP_OPT_EVENTLIST  (1 << 11)
00879 #define SIP_OPT_GRUU    (1 << 12)
00880 #define SIP_OPT_TARGET_DIALOG (1 << 13)
00881 #define SIP_OPT_NOREFERSUB (1 << 14)
00882 #define SIP_OPT_HISTINFO   (1 << 15)
00883 #define SIP_OPT_RESPRIORITY   (1 << 16)
00884 #define SIP_OPT_FROMCHANGE (1 << 17)
00885 #define SIP_OPT_RECLISTINV (1 << 18)
00886 #define SIP_OPT_RECLISTSUB (1 << 19)
00887 #define SIP_OPT_OUTBOUND   (1 << 20)
00888 #define SIP_OPT_UNKNOWN    (1 << 21)
00889 
00890 
00891 /*! \brief List of well-known SIP options. If we get this in a require,
00892    we should check the list and answer accordingly. */
00893 static const struct cfsip_options {
00894    int id;        /*!< Bitmap ID */
00895    int supported;    /*!< Supported by Asterisk ? */
00896    char * const text;   /*!< Text id, as in standard */
00897 } sip_options[] = {  /* XXX used in 3 places */
00898    /* RFC3262: PRACK 100% reliability */
00899    { SIP_OPT_100REL, NOT_SUPPORTED, "100rel" }, 
00900    /* RFC3959: SIP Early session support */
00901    { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,   "early-session" },
00902    /* SIMPLE events:  RFC4662 */
00903    { SIP_OPT_EVENTLIST, NOT_SUPPORTED, "eventlist" },
00904    /* RFC 4916- Connected line ID updates */
00905    { SIP_OPT_FROMCHANGE,   NOT_SUPPORTED, "from-change" },
00906    /* GRUU: Globally Routable User Agent URI's */
00907    { SIP_OPT_GRUU,      NOT_SUPPORTED, "gruu" },
00908    /* RFC4244 History info */
00909    { SIP_OPT_HISTINFO,  NOT_SUPPORTED, "histinfo" },
00910    /* RFC3911: SIP Join header support */
00911    { SIP_OPT_JOIN,      NOT_SUPPORTED, "join" },
00912    /* Disable the REFER subscription, RFC 4488 */
00913    { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED, "norefersub" },
00914    /* SIP outbound - the final NAT battle - draft-sip-outbound */
00915    { SIP_OPT_OUTBOUND,  NOT_SUPPORTED, "outbound" },
00916    /* RFC3327: Path support */
00917    { SIP_OPT_PATH,      NOT_SUPPORTED, "path" },
00918    /* RFC3840: Callee preferences */
00919    { SIP_OPT_PREF,      NOT_SUPPORTED, "pref" },
00920    /* RFC3312: Precondition support */
00921    { SIP_OPT_PRECONDITION, NOT_SUPPORTED, "precondition" },
00922    /* RFC3323: Privacy with proxies*/
00923    { SIP_OPT_PRIVACY,   NOT_SUPPORTED, "privacy" },
00924    /* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
00925    { SIP_OPT_RECLISTINV,   NOT_SUPPORTED, "recipient-list-invite" },
00926    /* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
00927    { SIP_OPT_RECLISTSUB,   NOT_SUPPORTED, "recipient-list-subscribe" },
00928    /* RFC3891: Replaces: header for transfer */
00929    { SIP_OPT_REPLACES,  SUPPORTED,  "replaces" },  
00930    /* One version of Polycom firmware has the wrong label */
00931    { SIP_OPT_REPLACES,  SUPPORTED,  "replace" },   
00932    /* RFC4412 Resource priorities */
00933    { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED, "resource-priority" },
00934    /* RFC3329: Security agreement mechanism */
00935    { SIP_OPT_SEC_AGREE, NOT_SUPPORTED, "sec_agree" },
00936    /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
00937    { SIP_OPT_SDP_ANAT,  NOT_SUPPORTED, "sdp-anat" },
00938    /* RFC4028: SIP Session-Timers */
00939    { SIP_OPT_TIMER,  SUPPORTED,  "timer" },
00940    /* RFC4538: Target-dialog */
00941    { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED, "tdialog" },
00942 };
00943 
00944 
00945 /*! \brief SIP Methods we support 
00946    \todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
00947    allowsubscribe and allowrefer on in sip.conf.
00948 */
00949 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
00950 
00951 /*! \brief SIP Extensions we support 
00952    \note This should be generated based on the previous array
00953       in combination with settings.
00954    \todo We should not have "timer" if it's disabled in the configuration file.
00955 */
00956 #define SUPPORTED_EXTENSIONS "replaces, timer" 
00957 
00958 /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
00959 #define STANDARD_SIP_PORT  5060
00960 /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
00961 #define STANDARD_TLS_PORT  5061
00962 
00963 /*! \note in many SIP headers, absence of a port number implies port 5060,
00964  * and this is why we cannot change the above constant.
00965  * There is a limited number of places in asterisk where we could,
00966  * in principle, use a different "default" port number, but
00967  * we do not support this feature at the moment.
00968  * You can run Asterisk with SIP on a different port with a configuration
00969  * option. If you change this value, the signalling will be incorrect.
00970  */
00971 
00972 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
00973 
00974    These are default values in the source. There are other recommended values in the
00975    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
00976    yet encouraging new behaviour on new installations 
00977  */
00978 /*@{*/ 
00979 #define DEFAULT_CONTEXT    "default"   /*!< The default context for [general] section as well as devices */
00980 #define DEFAULT_MOHINTERPRET    "default" /*!< The default music class */
00981 #define DEFAULT_MOHSUGGEST      ""
00982 #define DEFAULT_VMEXTEN    "asterisk"  /*!< Default voicemail extension */
00983 #define DEFAULT_CALLERID   "asterisk"  /*!< Default caller ID */
00984 #define DEFAULT_NOTIFYMIME    "application/simple-message-summary"
00985 #define DEFAULT_ALLOWGUEST TRUE
00986 #define DEFAULT_RTPKEEPALIVE  0     /*!< Default RTPkeepalive setting */
00987 #define DEFAULT_CALLCOUNTER   FALSE
00988 #define DEFAULT_SRVLOOKUP  TRUE     /*!< Recommended setting is ON */
00989 #define DEFAULT_COMPACTHEADERS   FALSE    /*!< Send compact (one-character) SIP headers. Default off */
00990 #define DEFAULT_TOS_SIP         0               /*!< Call signalling packets should be marked as DSCP CS3, but the default is 0 to be compatible with previous versions. */
00991 #define DEFAULT_TOS_AUDIO       0               /*!< Audio packets should be marked as DSCP EF (Expedited Forwarding), but the default is 0 to be compatible with previous versions. */
00992 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
00993 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
00994 #define DEFAULT_COS_SIP         4      /*!< Level 2 class of service for SIP signalling */
00995 #define DEFAULT_COS_AUDIO       5      /*!< Level 2 class of service for audio media  */
00996 #define DEFAULT_COS_VIDEO       6      /*!< Level 2 class of service for video media */
00997 #define DEFAULT_COS_TEXT        5      /*!< Level 2 class of service for text media (T.140) */
00998 #define DEFAULT_ALLOW_EXT_DOM TRUE     /*!< Allow external domains */
00999 #define DEFAULT_REALM      "asterisk"  /*!< Realm for HTTP digest authentication */
01000 #define DEFAULT_NOTIFYRINGING TRUE     /*!< Notify devicestate system on ringing state */
01001 #define DEFAULT_NOTIFYCID     DISABLED /*!< Include CID with ringing notifications */
01002 #define DEFAULT_PEDANTIC   FALSE    /*!< Avoid following SIP standards for dialog matching */
01003 #define DEFAULT_AUTOCREATEPEER   FALSE    /*!< Don't create peers automagically */
01004 #define  DEFAULT_MATCHEXTERNIPLOCALLY FALSE  /*!< Match extern IP locally default setting */
01005 #define DEFAULT_QUALIFY    FALSE    /*!< Don't monitor devices */
01006 #define DEFAULT_CALLEVENTS FALSE    /*!< Extra manager SIP call events */
01007 #define DEFAULT_ALWAYSAUTHREJECT FALSE /*!< Don't reject authentication requests always */
01008 #define DEFAULT_REGEXTENONQUALIFY FALSE
01009 #define DEFAULT_T1MIN      100      /*!< 100 MS for minimal roundtrip time */
01010 #define DEFAULT_MAX_CALL_BITRATE (384)    /*!< Max bitrate for video */
01011 #ifndef DEFAULT_USERAGENT
01012 #define DEFAULT_USERAGENT "Asterisk PBX"  /*!< Default Useragent: header unless re-defined in sip.conf */
01013 #define DEFAULT_SDPSESSION "Asterisk PBX" /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
01014 #define DEFAULT_SDPOWNER "root"        /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
01015 #endif
01016 /*@}*/ 
01017 
01018 /*! \name DefaultSettings
01019    Default setttings are used as a channel setting and as a default when
01020    configuring devices 
01021 */
01022 /*@{*/ 
01023 static char default_language[MAX_LANGUAGE];
01024 static char default_callerid[AST_MAX_EXTENSION];
01025 static char default_fromdomain[AST_MAX_EXTENSION];
01026 static char default_notifymime[AST_MAX_EXTENSION];
01027 static int default_qualify;      /*!< Default Qualify= setting */
01028 static char default_vmexten[AST_MAX_EXTENSION];
01029 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
01030 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
01031                                                     *   a bridged channel on hold */
01032 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
01033 static int default_maxcallbitrate;  /*!< Maximum bitrate for call */
01034 static struct ast_codec_pref default_prefs;     /*!< Default codec prefs */
01035 static unsigned int default_transports;         /*!< Default Transports (enum sip_transport) that are acceptable */
01036 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
01037 
01038 /*@}*/ 
01039 
01040 /*! \name GlobalSettings
01041    Global settings apply to the channel (often settings you can change in the general section
01042    of sip.conf
01043 */
01044 /*@{*/ 
01045 /*! \brief a place to store all global settings for the sip channel driver 
01046    These are settings that will be possibly to apply on a group level later on.
01047    \note Do not add settings that only apply to the channel itself and can't
01048          be applied to devices (trunks, services, phones)
01049 */
01050 struct sip_settings {
01051    int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
01052    int rtsave_sysname;     /*!< G: Save system name at registration? */
01053    int ignore_regexpire;      /*!< G: Ignore expiration of peer  */
01054    int rtautoclear;     /*!< Realtime ?? */
01055    int directrtpsetup;     /*!< Enable support for Direct RTP setup (no re-invites) */
01056    int pedanticsipchecking;   /*!< Extra checking ?  Default off */
01057    int autocreatepeer;     /*!< Auto creation of peers at registration? Default off. */
01058    int srvlookup;       /*!< SRV Lookup on or off. Default is on */
01059    int allowguest;         /*!< allow unauthenticated peers to connect? */
01060    int alwaysauthreject;      /*!< Send 401 Unauthorized for all failing requests */
01061    int compactheaders;     /*!< send compact sip headers */
01062    int allow_external_domains;   /*!< Accept calls to external SIP domains? */
01063    int callevents;         /*!< Whether we send manager events or not */
01064    int regextenonqualify;     /*!< Whether to add/remove regexten when qualifying peers */
01065    int matchexterniplocally;  /*!< Match externip/externhost setting against localnet setting */
01066    int notifyringing;      /*!< Send notifications on ringing */
01067    int notifyhold;         /*!< Send notifications on hold */
01068    enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
01069    enum transfermodes allowtransfer;   /*!< SIP Refer restriction scheme */
01070    int allowsubscribe;          /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
01071                    the global setting is in globals_flags[1] */
01072    char realm[MAXHOSTNAMELEN];      /*!< Default realm */
01073    struct sip_proxy outboundproxy;  /*!< Outbound proxy */
01074    char default_context[AST_MAX_CONTEXT];
01075    char default_subscribecontext[AST_MAX_CONTEXT];
01076 };
01077 
01078 static struct sip_settings sip_cfg;
01079 
01080 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
01081 
01082 static int global_relaxdtmf;     /*!< Relax DTMF */
01083 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
01084 static int global_relaxdtmf;        /*!< Relax DTMF */
01085 static int global_rtptimeout;    /*!< Time out call if no RTP */
01086 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
01087 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
01088 static int global_reg_timeout;
01089 static int global_regattempts_max;  /*!< Registration attempts before giving up */
01090 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
01091 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
01092                   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
01093                   with just a boolean flag in the device structure */
01094 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
01095 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
01096 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
01097 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
01098 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
01099 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
01100 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
01101 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
01102 static int recordhistory;     /*!< Record SIP history. Off by default */
01103 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
01104 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
01105 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
01106 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
01107 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
01108 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
01109 static int global_t1;         /*!< T1 time */
01110 static int global_t1min;      /*!< T1 roundtrip time minimum */
01111 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
01112 static int global_autoframing;            /*!< Turn autoframing on or off. */
01113 static int global_qualifyfreq;         /*!< Qualify frequency */
01114 static int global_qualify_gap;              /*!< Time between our group of peer pokes */
01115 static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
01116 
01117 
01118 /*! \brief Codecs that we support by default: */
01119 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
01120 
01121 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
01122 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
01123 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
01124 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
01125 
01126 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
01127 /*@}*/
01128 
01129 /*! \brief Global list of addresses dynamic peers are not allowed to use */
01130 static struct ast_ha *global_contact_ha = NULL;
01131 
01132 /*! \name Object counters @{
01133  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
01134  * should be used to modify these values. */
01135 static int speerobjs = 0;                /*!< Static peers */
01136 static int rpeerobjs = 0;                /*!< Realtime peers */
01137 static int apeerobjs = 0;                /*!< Autocreated peer objects */
01138 static int regobjs = 0;                  /*!< Registry objects */
01139 /* }@ */
01140 
01141 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
01142 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
01143 
01144 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
01145 
01146 
01147 AST_MUTEX_DEFINE_STATIC(netlock);
01148 
01149 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
01150    when it's doing something critical. */
01151 AST_MUTEX_DEFINE_STATIC(monlock);
01152 
01153 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
01154 
01155 /*! \brief This is the thread for the monitor which checks for input on the channels
01156    which are not currently in use.  */
01157 static pthread_t monitor_thread = AST_PTHREADT_NULL;
01158 
01159 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
01160 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
01161 
01162 static struct sched_context *sched;     /*!< The scheduling context */
01163 static struct io_context *io;           /*!< The IO context */
01164 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
01165 
01166 #define DEC_CALL_LIMIT  0
01167 #define INC_CALL_LIMIT  1
01168 #define DEC_CALL_RINGING 2
01169 #define INC_CALL_RINGING 3
01170 
01171 /*! \brief The SIP socket definition */
01172 struct sip_socket {
01173    enum sip_transport type;   /*!< UDP, TCP or TLS */
01174    int fd;           /*!< Filed descriptor, the actual socket */
01175    uint16_t port;
01176    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
01177 };
01178 
01179 /*! \brief sip_request: The data grabbed from the UDP socket
01180  *
01181  * \verbatim
01182  * Incoming messages: we first store the data from the socket in data[],
01183  * adding a trailing \0 to make string parsing routines happy.
01184  * Then call parse_request() and req.method = find_sip_method();
01185  * to initialize the other fields. The \r\n at the end of each line is   
01186  * replaced by \0, so that data[] is not a conforming SIP message anymore.
01187  * After this processing, rlPart1 is set to non-NULL to remember
01188  * that we can run get_header() on this kind of packet.
01189  *
01190  * parse_request() splits the first line as follows:
01191  * Requests have in the first line      method uri SIP/2.0
01192  *      rlPart1 = method; rlPart2 = uri;
01193  * Responses have in the first line     SIP/2.0 NNN description
01194  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
01195  *
01196  * For outgoing packets, we initialize the fields with init_req() or init_resp()
01197  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
01198  * and then fill the rest with add_header() and add_line().
01199  * The \r\n at the end of the line are still there, so the get_header()
01200  * and similar functions don't work on these packets. 
01201  * \endverbatim
01202  */
01203 struct sip_request {
01204    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
01205    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
01206    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
01207    int headers;            /*!< # of SIP Headers */
01208    int method;             /*!< Method of this request */
01209    int lines;              /*!< Body Content */
01210    unsigned int sdp_start; /*!< the line number where the SDP begins */
01211    unsigned int sdp_count; /*!< the number of lines of SDP */
01212    char debug;    /*!< print extra debugging if non zero */
01213    char has_to_tag;  /*!< non-zero if packet has To: tag */
01214    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
01215    /* Array of offsets into the request string of each SIP header*/
01216    ptrdiff_t header[SIP_MAX_HEADERS];
01217    /* Array of offsets into the request string of each SDP line*/
01218    ptrdiff_t line[SIP_MAX_LINES];
01219    struct ast_str *data;   
01220    /* XXX Do we need to unref socket.ser when the request goes away? */
01221    struct sip_socket socket;  /*!< The socket used for this request */
01222    AST_LIST_ENTRY(sip_request) next;
01223 };
01224 
01225 /* \brief given a sip_request and an offset, return the char * that resides there
01226  *
01227  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
01228  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
01229  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
01230  * provided to retrieve the string at a particular offset within the request's buffer
01231  */
01232 #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
01233 
01234 /*! \brief structure used in transfers */
01235 struct sip_dual {
01236    struct ast_channel *chan1; /*!< First channel involved */
01237    struct ast_channel *chan2; /*!< Second channel involved */
01238    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
01239    int seqno;        /*!< Sequence number */
01240 };
01241 
01242 struct sip_pkt;
01243 
01244 /*! \brief Parameters to the transmit_invite function */
01245 struct sip_invite_param {
01246    int addsipheaders;      /*!< Add extra SIP headers */
01247    const char *uri_options;   /*!< URI options to add to the URI */
01248    const char *vxml_url;      /*!< VXML url for Cisco phones */
01249    char *auth;       /*!< Authentication */
01250    char *authheader;    /*!< Auth header */
01251    enum sip_auth_type auth_type; /*!< Authentication type */
01252    const char *replaces;      /*!< Replaces header for call transfers */
01253    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
01254 };
01255 
01256 /*! \brief Structure to save routing information for a SIP session */
01257 struct sip_route {
01258    struct sip_route *next;
01259    char hop[0];
01260 };
01261 
01262 /*! \brief Modes for SIP domain handling in the PBX */
01263 enum domain_mode {
01264    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
01265    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
01266 };
01267 
01268 /*! \brief Domain data structure. 
01269    \note In the future, we will connect this to a configuration tree specific
01270    for this domain
01271 */
01272 struct domain {
01273    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
01274    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
01275    enum domain_mode mode;        /*!< How did we find this domain? */
01276    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
01277 };
01278 
01279 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
01280 
01281 
01282 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
01283 struct sip_history {
01284    AST_LIST_ENTRY(sip_history) list;
01285    char event[0]; /* actually more, depending on needs */
01286 };
01287 
01288 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
01289 
01290 /*! \brief sip_auth: Credentials for authentication to other SIP services */
01291 struct sip_auth {
01292    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
01293    char username[256];             /*!< Username */
01294    char secret[256];               /*!< Secret */
01295    char md5secret[256];            /*!< MD5Secret */
01296    struct sip_auth *next;          /*!< Next auth structure in list */
01297 };
01298 
01299 /*! \name SIPflags
01300    Various flags for the flags field in the pvt structure 
01301    Trying to sort these up (one or more of the following):
01302    D: Dialog
01303    P: Peer/user
01304    G: Global flag
01305    When flags are used by multiple structures, it is important that
01306    they have a common layout so it is easy to copy them.
01307 */
01308 /*@{*/ 
01309 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01310 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01311 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01312 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01313 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01314 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01315 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01316 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01317 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01318 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01319 
01320 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01321 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01322 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01323 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01324 
01325 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01326 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01327 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01328 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01329 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01330 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01331 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01332 
01333 /* NAT settings - see nat2str() */
01334 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01335 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01336 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01337 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01338 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01339 
01340 /* re-INVITE related settings */
01341 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01342 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01343 #define SIP_DIRECT_MEDIA   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01344 #define SIP_DIRECT_MEDIA_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01345 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01346 
01347 /* "insecure" settings - see insecure2str() */
01348 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01349 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01350 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01351 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01352 
01353 /* Sending PROGRESS in-band settings */
01354 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01355 #define SIP_PROG_INBAND_NEVER (0 << 25)
01356 #define SIP_PROG_INBAND_NO (1 << 25)
01357 #define SIP_PROG_INBAND_YES   (2 << 25)
01358 
01359 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01360 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01361 
01362 /*! \brief Flags to copy from peer/user to dialog */
01363 #define SIP_FLAGS_TO_COPY \
01364    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01365     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01366     SIP_USEREQPHONE | SIP_INSECURE)
01367 /*@}*/ 
01368 
01369 /*! \name SIPflags2
01370    a second page of flags (for flags[1] */
01371 /*@{*/ 
01372 /* realtime flags */
01373 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01374 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01375 /* Space for addition of other realtime flags in the future */
01376 #define SIP_PAGE2_CONSTANT_SSRC     (1 << 8) /*!< GDP: Don't change SSRC on reinvite */
01377 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01378 
01379 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01380 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01381 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01382 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01383 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01384 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01385 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01386 
01387 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01388 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01389 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01390 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01391 
01392 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01393 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01394 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01395 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01396 
01397 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01398 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01399 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01400 #define SIP_PAGE2_FAX_DETECT     (1 << 28)      /*!< DP: Fax Detection support */
01401 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01402 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01403 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01404 
01405 #define SIP_PAGE2_FLAGS_TO_COPY \
01406    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01407    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01408    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
01409    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_CONSTANT_SSRC)
01410 
01411 /*@}*/ 
01412 
01413 /*! \brief debugging state
01414  * We store separately the debugging requests from the config file
01415  * and requests from the CLI. Debugging is enabled if either is set
01416  * (which means that if sipdebug is set in the config file, we can
01417  * only turn it off by reloading the config).
01418  */
01419 enum sip_debug_e {
01420    sip_debug_none = 0,
01421    sip_debug_config = 1,
01422    sip_debug_console = 2,
01423 };
01424 
01425 static enum sip_debug_e sipdebug;
01426 
01427 /*! \brief extra debugging for 'text' related events.
01428  * At the moment this is set together with sip_debug_console.
01429  * \note It should either go away or be implemented properly.
01430  */
01431 static int sipdebug_text;
01432 
01433 /*! \brief T38 States for a call */
01434 enum t38state {
01435    T38_DISABLED = 0,                /*!< Not enabled */
01436    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01437    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01438    T38_ENABLED                      /*!< Negotiated (enabled) */
01439 };
01440 
01441 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01442 struct t38properties {
01443    enum t38state state;    /*!< T.38 state */
01444    struct ast_control_t38_parameters our_parms;
01445    struct ast_control_t38_parameters their_parms;
01446 };
01447 
01448 /*! \brief Parameters to know status of transfer */
01449 enum referstatus {
01450    REFER_IDLE,                    /*!< No REFER is in progress */
01451    REFER_SENT,                    /*!< Sent REFER to transferee */
01452    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01453    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01454    REFER_ACCEPTED,                /*!< Accepted by transferee */
01455    REFER_RINGING,                 /*!< Target Ringing */
01456    REFER_200OK,                   /*!< Answered by transfer target */
01457    REFER_FAILED,                  /*!< REFER declined - go on */
01458    REFER_NOAUTH                   /*!< We had no auth for REFER */
01459 };
01460 
01461 /*! \brief generic struct to map between strings and integers.
01462  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01463  * Then you can call map_x_s(...) to map an integer to a string,
01464  * and map_s_x() for the string -> integer mapping.
01465  */
01466 struct _map_x_s {
01467    int x;
01468    const char *s;
01469 };              
01470 
01471 static const struct _map_x_s referstatusstrings[] = {
01472    { REFER_IDLE,     "<none>" },
01473    { REFER_SENT,     "Request sent" },
01474    { REFER_RECEIVED, "Request received" },
01475    { REFER_CONFIRMED,   "Confirmed" },
01476    { REFER_ACCEPTED, "Accepted" },
01477    { REFER_RINGING,  "Target ringing" },
01478    { REFER_200OK,    "Done" },
01479    { REFER_FAILED,      "Failed" },
01480    { REFER_NOAUTH,      "Failed - auth failure" },
01481    { -1,       NULL} /* terminator */
01482 };
01483 
01484 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01485    \note OEJ: Should be moved to string fields */
01486 struct sip_refer {
01487    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01488    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01489    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01490    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01491    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01492    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01493    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01494    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01495    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01496    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01497    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01498                       * dialog owned by someone else, so we should not destroy
01499                       * it when the sip_refer object goes.
01500                       */
01501    int attendedtransfer;            /*!< Attended or blind transfer? */
01502    int localtransfer;            /*!< Transfer to local domain? */
01503    enum referstatus status;         /*!< REFER status */
01504 };
01505 
01506 
01507 /*! \brief Structure that encapsulates all attributes related to running 
01508  *   SIP Session-Timers feature on a per dialog basis.
01509  */
01510 struct sip_st_dlg {
01511    int st_active;                          /*!< Session-Timers on/off */ 
01512    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01513    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01514    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01515    int st_expirys;                         /*!< Session-Timers number of expirys */
01516    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01517    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01518    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01519    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01520    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01521    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01522 };
01523 
01524 
01525 /*! \brief Structure that encapsulates all attributes related to configuration 
01526  *   of SIP Session-Timers feature on a per user/peer basis.
01527  */
01528 struct sip_st_cfg {
01529    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01530    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01531    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01532    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01533 };
01534 
01535 struct offered_media {
01536    int offered;
01537    char text[128];
01538 };
01539 
01540 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01541  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01542  * descriptors (dialoglist).
01543  */
01544 struct sip_pvt {
01545    struct sip_pvt *next;         /*!< Next dialog in chain */
01546    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01547    int method;          /*!< SIP method that opened this dialog */
01548    AST_DECLARE_STRING_FIELDS(
01549       AST_STRING_FIELD(callid);  /*!< Global CallID */
01550       AST_STRING_FIELD(randdata);   /*!< Random data */
01551       AST_STRING_FIELD(accountcode);   /*!< Account code */
01552       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01553       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01554       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01555       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01556       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01557       AST_STRING_FIELD(from);    /*!< The From: header */
01558       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01559       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01560       AST_STRING_FIELD(context); /*!< Context for this call */
01561       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01562       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01563       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01564       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01565       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01566       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01567       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01568       AST_STRING_FIELD(language);   /*!< Default language for this call */
01569       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01570       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01571       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01572       AST_STRING_FIELD(redircause); /*!< Referring cause */
01573       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01574       AST_STRING_FIELD(username);   /*!< [user] name */
01575       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01576       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01577       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01578       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01579       AST_STRING_FIELD(peersecret); /*!< Password */
01580       AST_STRING_FIELD(peermd5secret);
01581       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01582       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01583       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01584          /* we only store the part in <brackets> in this field. */
01585       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01586       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01587       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01588       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01589       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01590    );
01591    char via[128];                          /*!< Via: header */
01592    struct sip_socket socket;     /*!< The socket used for this dialog */
01593    unsigned int ocseq;        /*!< Current outgoing seqno */
01594    unsigned int icseq;        /*!< Current incoming seqno */
01595    ast_group_t callgroup;        /*!< Call group */
01596    ast_group_t pickupgroup;      /*!< Pickup group */
01597    int lastinvite;            /*!< Last Cseq of invite */
01598    struct ast_flags flags[2];    /*!< SIP_ flags */
01599 
01600    /* boolean or small integers that don't belong in flags */
01601    char do_history;        /*!< Set if we want to record history */
01602    char alreadygone;       /*!< already destroyed by our peer */
01603    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01604    char outgoing_call;        /*!< this is an outgoing call */
01605    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01606    char novideo;           /*!< Didn't get video in invite, don't offer */
01607    char notext;            /*!< Text not supported  (?) */
01608 
01609    int timer_t1;           /*!< SIP timer T1, ms rtt */
01610    int timer_b;                            /*!< SIP timer B, ms */
01611    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01612    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01613    struct ast_codec_pref prefs;     /*!< codec prefs */
01614    int capability;            /*!< Special capability (codec) */
01615    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01616    int peercapability;        /*!< Supported peer capability */
01617    int prefcodec;          /*!< Preferred codec (outbound only) */
01618    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01619    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01620    int redircodecs;        /*!< Redirect codecs */
01621    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01622    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01623    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
01624    struct t38properties t38;     /*!< T38 settings */
01625    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01626    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01627    int callingpres;        /*!< Calling presentation */
01628    int authtries;          /*!< Times we've tried to authenticate */
01629    int expiry;          /*!< How long we take to expire */
01630    long branch;            /*!< The branch identifier of this session */
01631    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01632    char tag[11];           /*!< Our tag for this session */
01633    int sessionid;          /*!< SDP Session ID */
01634    int sessionversion;        /*!< SDP Session Version */
01635    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01636    int session_modify;        /*!< Session modification request true/false  */
01637    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01638    struct sockaddr_in sa;        /*!< Our peer */
01639    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01640    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01641    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01642    time_t lastrtprx;       /*!< Last RTP received */
01643    time_t lastrtptx;       /*!< Last RTP sent */
01644    int rtptimeout;            /*!< RTP timeout time */
01645    struct sockaddr_in recv;      /*!< Received as */
01646    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01647    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01648    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01649    int route_persistant;         /*!< Is this the "real" route? */
01650    struct ast_variable *notify_headers;    /*!< Custom notify type */
01651    struct sip_auth *peerauth;    /*!< Realm authentication */
01652    int noncecount;            /*!< Nonce-count */
01653    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01654    char lastmsg[256];         /*!< Last Message sent/received */
01655    int amaflags;           /*!< AMA Flags */
01656    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01657    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01658                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01659                   held in order to properly process acknowledgements for our 491 response. */
01660    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01661                      within this dialog.
01662                      NOT the request that opened the dialog */
01663 
01664    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01665    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01666    int autokillid;            /*!< Auto-kill ID (scheduler) */
01667    int t38id;                              /*!< T.38 Response ID */
01668    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01669    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01670    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01671    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01672    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01673    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01674 
01675    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01676 
01677    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01678                      Used in peerpoke, mwi subscriptions */
01679    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01680    struct ast_rtp *rtp;       /*!< RTP Session */
01681    struct ast_rtp *vrtp;         /*!< Video RTP session */
01682    struct ast_rtp *trtp;         /*!< Text RTP session */
01683    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01684    struct sip_history_head *history;   /*!< History of this SIP dialog */
01685    size_t history_entries;       /*!< Number of entires in the history */
01686    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01687    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01688    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01689    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01690    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01691    struct sip_invite_param *options;   /*!< Options for INVITE */
01692    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01693                      before strolling to the Grokyzpå
01694                      (A bit unsure of this, please correct if
01695                      you know more) */
01696    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01697   
01698    int red;             /*!< T.140 RTP Redundancy */
01699    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01700 
01701    struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
01702    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01703     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01704     * still put an m= line in our answer with the port set to 0.
01705     *
01706     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01707     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01708     *
01709     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01710     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01711     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01712     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01713     *
01714     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01715     */
01716    struct offered_media offered_media[4];
01717 }; 
01718 
01719 
01720 /*! \brief
01721  * Here we implement the container for dialogs (sip_pvt), defining
01722  * generic wrapper functions to ease the transition from the current
01723  * implementation (a single linked list) to a different container.
01724  * In addition to a reference to the container, we need functions to lock/unlock
01725  * the container and individual items, and functions to add/remove
01726  * references to the individual items.
01727  */
01728 struct ao2_container *dialogs;
01729 
01730 #define sip_pvt_lock(x) ao2_lock(x)
01731 #define sip_pvt_trylock(x) ao2_trylock(x)
01732 #define sip_pvt_unlock(x) ao2_unlock(x)
01733 
01734 /*! \brief
01735  * when we create or delete references, make sure to use these
01736  * functions so we keep track of the refcounts.
01737  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01738  */
01739 #ifdef REF_DEBUG
01740 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01741 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01742 
01743 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01744 {
01745    if (p)
01746       _ao2_ref_debug(p, 1, tag, file, line, func);
01747    else
01748       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01749    return p;
01750 }
01751 
01752 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01753 {
01754    if (p)
01755       _ao2_ref_debug(p, -1, tag, file, line, func);
01756    return NULL;
01757 }
01758 #else
01759 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01760 {
01761    if (p)
01762       ao2_ref(p, 1);
01763    else
01764       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01765    return p;
01766 }
01767 
01768 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01769 {
01770    if (p)
01771       ao2_ref(p, -1);
01772    return NULL;
01773 }
01774 #endif
01775 
01776 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01777  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01778  * Each packet holds a reference to the parent struct sip_pvt.
01779  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01780  * require retransmissions.
01781  */
01782 struct sip_pkt {
01783    struct sip_pkt *next;         /*!< Next packet in linked list */
01784    int retrans;            /*!< Retransmission number */
01785    int method;          /*!< SIP method for this packet */
01786    int seqno;           /*!< Sequence number */
01787    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01788    char is_fatal;          /*!< non-zero if there is a fatal error */
01789    int response_code;      /*!< If this is a response, the response code */
01790    struct sip_pvt *owner;        /*!< Owner AST call */
01791    int retransid;          /*!< Retransmission ID */
01792    int timer_a;            /*!< SIP timer A, retransmission timer */
01793    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01794    int packetlen;          /*!< Length of packet */
01795    struct ast_str *data;
01796 }; 
01797 
01798 /*!
01799  * \brief A peer's mailbox
01800  *
01801  * We could use STRINGFIELDS here, but for only two strings, it seems like
01802  * too much effort ...
01803  */
01804 struct sip_mailbox {
01805    char *mailbox;
01806    char *context;
01807    /*! Associated MWI subscription */
01808    struct ast_event_sub *event_sub;
01809    AST_LIST_ENTRY(sip_mailbox) entry;
01810 };
01811 
01812 enum sip_peer_type {
01813    SIP_TYPE_PEER = (1 << 0),
01814    SIP_TYPE_USER = (1 << 1),
01815 };
01816 
01817 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01818 */
01819 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01820 struct sip_peer {
01821    char name[80];             /*!< the unique name of this object */
01822    AST_DECLARE_STRING_FIELDS(
01823       AST_STRING_FIELD(secret);     /*!< Password for inbound auth */
01824       AST_STRING_FIELD(md5secret);     /*!< Password in MD5 */
01825       AST_STRING_FIELD(remotesecret);     /*!< Remote secret (trunks, remote devices) */
01826       AST_STRING_FIELD(context);    /*!< Default context for incoming calls */
01827       AST_STRING_FIELD(subscribecontext); /*!< Default context for subscriptions */
01828       AST_STRING_FIELD(username);      /*!< Temporary username until registration */ 
01829       AST_STRING_FIELD(accountcode);      /*!< Account code */
01830       AST_STRING_FIELD(tohost);     /*!< If not dynamic, IP address */
01831       AST_STRING_FIELD(regexten);      /*!< Extension to register (if regcontext is used) */
01832       AST_STRING_FIELD(fromuser);      /*!< From: user when calling this peer */
01833       AST_STRING_FIELD(fromdomain);    /*!< From: domain when calling this peer */
01834       AST_STRING_FIELD(fullcontact);      /*!< Contact registered with us (not in sip.conf) */
01835       AST_STRING_FIELD(cid_num);    /*!< Caller ID num */
01836       AST_STRING_FIELD(cid_name);      /*!< Caller ID name */
01837       AST_STRING_FIELD(vmexten);       /*!< Dialplan extension for MWI notify message*/
01838       AST_STRING_FIELD(language);      /*!<  Default language for prompts */
01839       AST_STRING_FIELD(mohinterpret);     /*!<  Music on Hold class */
01840       AST_STRING_FIELD(mohsuggest);    /*!<  Music on Hold class */
01841       AST_STRING_FIELD(parkinglot);    /*!<  Parkinglot */
01842       AST_STRING_FIELD(useragent);     /*!<  User agent in SIP request (saved from registration) */
01843       );
01844    struct sip_socket socket;  /*!< Socket used for this peer */
01845    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
01846                                     If register expires, default should be reset. to this value */
01847    unsigned int transports:3;      /*!< Transports (enum sip_transport) that are acceptable for this peer */
01848    struct sip_auth *auth;     /*!< Realm authentication list */
01849    int amaflags;        /*!< AMA Flags (for billing) */
01850    int callingpres;     /*!< Calling id presentation */
01851    int inUse;        /*!< Number of calls in use */
01852    int inRinging;       /*!< Number of calls ringing */
01853    int onHold;                     /*!< Peer has someone on hold */
01854    int call_limit;         /*!< Limit of concurrent calls */
01855    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01856    int busy_level;         /*!< Level of active channels where we signal busy */
01857    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01858    struct ast_codec_pref prefs;  /*!<  codec prefs */
01859    int lastmsgssent;
01860    unsigned int sipoptions;   /*!<  Supported SIP options */
01861    struct ast_flags flags[2]; /*!<  SIP_ flags */
01862 
01863    /*! Mailboxes that this peer cares about */
01864    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01865 
01866    /* things that don't belong in flags */
01867    char is_realtime;    /*!< this is a 'realtime' peer */
01868    char rt_fromcontact;    /*!< copy fromcontact from realtime */
01869    char host_dynamic;      /*!< Dynamic Peers register with Asterisk */
01870    char selfdestruct;      /*!< Automatic peers need to destruct themselves */
01871    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01872 
01873    int expire;       /*!<  When to expire this peer registration */
01874    int capability;         /*!<  Codec capability */
01875    int rtptimeout;         /*!<  RTP timeout */
01876    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01877    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01878    ast_group_t callgroup;     /*!<  Call group */
01879    ast_group_t pickupgroup;   /*!<  Pickup group */
01880    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01881    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01882    struct sockaddr_in addr;   /*!<  IP address of peer */
01883    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01884    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01885 
01886    /* Qualification */
01887    struct sip_pvt *call;      /*!<  Call pointer */
01888    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01889    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01890    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01891    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01892    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01893    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01894    struct ast_ha *ha;      /*!<  Access control list */
01895    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01896    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01897    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01898    int autoframing;
01899    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01900    int timer_t1;        /*!<  The maximum T1 value for the peer */
01901    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01902    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01903    
01904    /*XXX Seems like we suddenly have two flags with the same content. Why? To be continued... */
01905    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01906 };
01907 
01908 
01909 /*! 
01910  * \brief Registrations with other SIP proxies
01911  *
01912  * Created by sip_register(), the entry is linked in the 'regl' list,
01913  * and never deleted (other than at 'sip reload' or module unload times).
01914  * The entry always has a pending timeout, either waiting for an ACK to
01915  * the REGISTER message (in which case we have to retransmit the request),
01916  * or waiting for the next REGISTER message to be sent (either the initial one,
01917  * or once the previously completed registration one expires).
01918  * The registration can be in one of many states, though at the moment
01919  * the handling is a bit mixed.
01920  */
01921 struct sip_registry {
01922    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01923    AST_DECLARE_STRING_FIELDS(
01924       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01925       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01926       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01927       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01928       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01929       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01930       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01931       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01932       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01933       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01934       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01935       AST_STRING_FIELD(callback);   /*!< Contact extension */
01936       AST_STRING_FIELD(random);
01937       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01938    );
01939    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01940    int portno;       /*!<  Optional port override */
01941    int expire;       /*!< Sched ID of expiration */
01942    int configured_expiry;     /*!< Configured value to use for the Expires header */
01943    int expiry;       /*!< Negotiated value used for the Expires header */
01944    int regattempts;     /*!< Number of attempts (since the last success) */
01945    int timeout;         /*!< sched id of sip_reg_timeout */
01946    int refresh;         /*!< How often to refresh */
01947    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01948    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01949    struct timeval regtime;    /*!< Last successful registration time */
01950    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01951    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01952    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01953    struct sockaddr_in us;     /*!< Who the server thinks we are */
01954    int noncecount;         /*!< Nonce-count */
01955    char lastmsg[256];      /*!< Last Message sent/received */
01956 };
01957 
01958 enum sip_tcptls_alert {
01959    /*! \brief There is new data to be sent out */
01960    TCPTLS_ALERT_DATA,
01961    /*! \brief A request to stop the tcp_handler thread */
01962    TCPTLS_ALERT_STOP,
01963 };
01964 
01965 struct tcptls_packet {
01966    AST_LIST_ENTRY(tcptls_packet) entry;
01967    struct ast_str *data;
01968    size_t len;
01969 };
01970 /*! \brief Definition of a thread that handles a socket */
01971 struct sip_threadinfo {
01972    int stop;
01973    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01974    pthread_t threadid;
01975    struct ast_tcptls_session_instance *tcptls_session;
01976    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01977    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01978 };
01979 
01980 /*! \brief Definition of an MWI subscription to another server */
01981 struct sip_subscription_mwi {
01982    ASTOBJ_COMPONENTS_FULL(struct sip_subscription_mwi,1,1);
01983    AST_DECLARE_STRING_FIELDS(
01984       AST_STRING_FIELD(username);     /*!< Who we are sending the subscription as */
01985       AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
01986       AST_STRING_FIELD(hostname);     /*!< Domain or host we subscribe to */
01987       AST_STRING_FIELD(secret);       /*!< Password in clear text */
01988       AST_STRING_FIELD(mailbox);      /*!< Mailbox store to put MWI into */
01989       );
01990    enum sip_transport transport;    /*!< Transport to use */
01991    int portno;                      /*!< Optional port override */
01992    int resub;                       /*!< Sched ID of resubscription */
01993    unsigned int subscribed:1;       /*!< Whether we are currently subscribed or not */
01994    struct sip_pvt *call;            /*!< Outbound subscription dialog */
01995    struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager for subscription */
01996    struct sockaddr_in us;           /*!< Who the server thinks we are */
01997 };
01998 
01999 /* --- Hash tables of various objects --------*/
02000 
02001 #ifdef LOW_MEMORY
02002 static int hash_peer_size = 17;
02003 static int hash_dialog_size = 17;
02004 static int hash_user_size = 17;
02005 #else
02006 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
02007 static int hash_dialog_size = 563;
02008 static int hash_user_size = 563;
02009 #endif
02010 
02011 /*! \brief  The table of TCP threads */
02012 static struct ao2_container *threadt;
02013 
02014 /*! \brief  The peer list: Users, Peers and Friends */
02015 struct ao2_container *peers;
02016 struct ao2_container *peers_by_ip;
02017 
02018 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
02019 static struct ast_register_list {
02020    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
02021    int recheck;
02022 } regl;
02023 
02024 /*! \brief  The MWI subscription list */
02025 static struct ast_subscription_mwi_list {
02026    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
02027 } submwil;
02028 
02029 /*! \brief
02030  * \note The only member of the peer used here is the name field
02031  */
02032 static int peer_hash_cb(const void *obj, const int flags)
02033 {
02034    const struct sip_peer *peer = obj;
02035 
02036    return ast_str_case_hash(peer->name);
02037 }
02038 
02039 /*!
02040  * \note The only member of the peer used here is the name field
02041  */
02042 static int peer_cmp_cb(void *obj, void *arg, int flags)
02043 {
02044    struct sip_peer *peer = obj, *peer2 = arg;
02045 
02046    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
02047 }
02048 
02049 /*!
02050  * \note the peer's ip address field is used to create key.
02051  */
02052 static int peer_iphash_cb(const void *obj, const int flags)
02053 {
02054    const struct sip_peer *peer = obj;
02055    int ret1 = peer->addr.sin_addr.s_addr;
02056    if (ret1 < 0)
02057       ret1 = -ret1;
02058 
02059    return ret1;
02060 }
02061 
02062 /*!
02063  * Match Peers by IP and Port number.
02064  *
02065  * This function has two modes.
02066  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
02067  *    a match for a peer that matches both the IP and port.
02068  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
02069  *    return a match for a peer that matches the IP and has insecure=port
02070  *    in its configuration.
02071  *
02072  * This callback will be used twice when doing peer matching.  There is a first
02073  * pass for full IP+port matching, and a second pass in case there is a match
02074  * that meets the insecure=port criteria.
02075  *
02076  * \note Connections coming in over TCP or TLS should never be matched by port.
02077  *
02078  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
02079  */
02080 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
02081 {
02082    struct sip_peer *peer = obj, *peer2 = arg;
02083 
02084    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
02085       /* IP doesn't match */
02086       return 0;
02087    }
02088 
02089    /* We matched the IP, check to see if we need to match by port as well. */
02090    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
02091       /* peer matching on port is not possible with TCP/TLS */
02092       return CMP_MATCH | CMP_STOP;
02093    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
02094       /* We are allowing match without port for peers configured that
02095        * way in this pass through the peers. */
02096       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
02097             (CMP_MATCH | CMP_STOP) : 0;
02098    }
02099 
02100    /* Now only return a match if the port matches, as well. */
02101    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
02102 }
02103 
02104 
02105 static int threadt_hash_cb(const void *obj, const int flags)
02106 {
02107    const struct sip_threadinfo *th = obj;
02108 
02109    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
02110 }
02111 
02112 static int threadt_cmp_cb(void *obj, void *arg, int flags)
02113 {
02114    struct sip_threadinfo *th = obj, *th2 = arg;
02115 
02116    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
02117 }
02118 
02119 /*!
02120  * \note The only member of the dialog used here callid string
02121  */
02122 static int dialog_hash_cb(const void *obj, const int flags)
02123 {
02124    const struct sip_pvt *pvt = obj;
02125 
02126    return ast_str_case_hash(pvt->callid);
02127 }
02128 
02129 /*!
02130  * \note The only member of the dialog used here callid string
02131  */
02132 static int dialog_cmp_cb(void *obj, void *arg, int flags)
02133 {
02134    struct sip_pvt *pvt = obj, *pvt2 = arg;
02135    
02136    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
02137 }
02138 
02139 static int temp_pvt_init(void *);
02140 static void temp_pvt_cleanup(void *);
02141 
02142 /*! \brief A per-thread temporary pvt structure */
02143 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
02144 
02145 #ifdef LOW_MEMORY
02146 static void ts_ast_rtp_destroy(void *);
02147 
02148 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
02149 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
02150 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
02151 #endif
02152 
02153 /*! \brief Authentication list for realm authentication 
02154  * \todo Move the sip_auth list to AST_LIST */
02155 static struct sip_auth *authl = NULL;
02156 
02157 
02158 /* --- Sockets and networking --------------*/
02159 
02160 /*! \brief Main socket for UDP SIP communication.
02161  *
02162  * sipsock is shared between the SIP manager thread (which handles reload
02163  * requests), the udp io handler (sipsock_read()) and the user routines that
02164  * issue udp writes (using __sip_xmit()).
02165  * The socket is -1 only when opening fails (this is a permanent condition),
02166  * or when we are handling a reload() that changes its address (this is
02167  * a transient situation during which we might have a harmless race, see
02168  * below). Because the conditions for the race to be possible are extremely
02169  * rare, we don't want to pay the cost of locking on every I/O.
02170  * Rather, we remember that when the race may occur, communication is
02171  * bound to fail anyways, so we just live with this event and let
02172  * the protocol handle this above us.
02173  */
02174 static int sipsock  = -1;
02175 
02176 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
02177 
02178 /*! \brief our (internal) default address/port to put in SIP/SDP messages
02179  *  internip is initialized picking a suitable address from one of the
02180  * interfaces, and the same port number we bind to. It is used as the
02181  * default address/port in SIP messages, and as the default address
02182  * (but not port) in SDP messages.
02183  */
02184 static struct sockaddr_in internip;
02185 
02186 /*! \brief our external IP address/port for SIP sessions.
02187  * externip.sin_addr is only set when we know we might be behind
02188  * a NAT, and this is done using a variety of (mutually exclusive)
02189  * ways from the config file:
02190  *
02191  * + with "externip = host[:port]" we specify the address/port explicitly.
02192  *   The address is looked up only once when (re)loading the config file;
02193  * 
02194  * + with "externhost = host[:port]" we do a similar thing, but the
02195  *   hostname is stored in externhost, and the hostname->IP mapping
02196  *   is refreshed every 'externrefresh' seconds;
02197  * 
02198  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
02199  *   to the specified server, and store the result in externip.
02200  *
02201  * Other variables (externhost, externexpire, externrefresh) are used
02202  * to support the above functions.
02203  */
02204 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
02205 
02206 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
02207 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
02208 static int externrefresh = 10;
02209 static struct sockaddr_in stunaddr;    /*!< stun server address */
02210 
02211 /*! \brief  List of local networks
02212  * We store "localnet" addresses from the config file into an access list,
02213  * marked as 'DENY', so the call to ast_apply_ha() will return
02214  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
02215  * (i.e. presumably public) addresses.
02216  */
02217 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
02218 
02219 static int ourport_tcp;          /*!< The port used for TCP connections */
02220 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
02221 static struct sockaddr_in debugaddr;
02222 
02223 static struct ast_config *notify_types = NULL;     /*!< The list of manual NOTIFY types we know how to send */
02224 
02225 /*! some list management macros. */
02226  
02227 #define UNLINK(element, head, prev) do {  \
02228    if (prev)            \
02229       (prev)->next = (element)->next;  \
02230    else              \
02231       (head) = (element)->next;  \
02232    } while (0)
02233 
02234 enum t38_action_flag {
02235    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
02236    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
02237    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
02238 };
02239 
02240 /*---------------------------- Forward declarations of functions in chan_sip.c */
02241 /* Note: This is added to help splitting up chan_sip.c into several files
02242    in coming releases. */
02243 
02244 /*--- PBX interface functions */
02245 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
02246 static int sip_devicestate(void *data);
02247 static int sip_sendtext(struct ast_channel *ast, const char *text);
02248 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
02249 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
02250 static int sip_hangup(struct ast_channel *ast);
02251 static int sip_answer(struct ast_channel *ast);
02252 static struct ast_frame *sip_read(struct ast_channel *ast);
02253 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
02254 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
02255 static int sip_transfer(struct ast_channel *ast, const char *dest);
02256 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
02257 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
02258 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
02259 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
02260 static const char *sip_get_callid(struct ast_channel *chan);
02261 
02262 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
02263 static int sip_standard_port(enum sip_transport type, int port);
02264 static int sip_prepare_socket(struct sip_pvt *p);
02265 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
02266 
02267 /*--- Transmitting responses and requests */
02268 static int sipsock_read(int *id, int fd, short events, void *ignore);
02269 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
02270 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
02271 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02272 static int retrans_pkt(const void *data);
02273 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
02274 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02275 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02276 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
02277 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
02278 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
02279 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
02280 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
02281 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
02282 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
02283 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
02284 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
02285 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
02286 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
02287 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
02288 static int transmit_info_with_vidupdate(struct sip_pvt *p);
02289 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
02290 static int transmit_refer(struct sip_pvt *p, const char *dest);
02291 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
02292 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
02293 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
02294 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
02295 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02296 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
02297 static void copy_request(struct sip_request *dst, const struct sip_request *src);
02298 static void receive_message(struct sip_pvt *p, struct sip_request *req);
02299 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
02300 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
02301 
02302 /*--- Dialog management */
02303 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
02304              int useglobal_nat, const int intended_method, struct sip_request *req);
02305 static int __sip_autodestruct(const void *data);
02306 static void sip_scheddestroy(struct sip_pvt *p, int ms);
02307 static int sip_cancel_destroy(struct sip_pvt *p);
02308 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
02309 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
02310 static void *registry_unref(struct sip_registry *reg, char *tag);
02311 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
02312 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02313 static void __sip_pretend_ack(struct sip_pvt *p);
02314 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
02315 static int auto_congest(const void *arg);
02316 static int update_call_counter(struct sip_pvt *fup, int event);
02317 static int hangup_sip2cause(int cause);
02318 static const char *hangup_cause2sip(int cause);
02319 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
02320 static void free_old_route(struct sip_route *route);
02321 static void list_route(struct sip_route *route);
02322 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
02323 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
02324                      struct sip_request *req, char *uri);
02325 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
02326 static void check_pendings(struct sip_pvt *p);
02327 static void *sip_park_thread(void *stuff);
02328 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
02329 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
02330 
02331 /*--- Codec handling / SDP */
02332 static void try_suggested_sip_codec(struct sip_pvt *p);
02333 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
02334 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
02335 static int find_sdp(struct sip_request *req);
02336 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
02337 static int process_sdp_o(const char *o, struct sip_pvt *p);
02338 static int process_sdp_c(const char *c, struct ast_hostent *hp);
02339 static int process_sdp_a_sendonly(const char *a, int *sendonly);
02340 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02341 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02342 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
02343 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02344 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
02345               struct ast_str **m_buf, struct ast_str **a_buf,
02346               int debug, int *min_packet_size);
02347 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
02348             struct ast_str **m_buf, struct ast_str **a_buf,
02349             int debug);
02350 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02351 static void do_setnat(struct sip_pvt *p, int natflags);
02352 static void stop_media_flows(struct sip_pvt *p);
02353 
02354 /*--- Authentication stuff */
02355 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02356 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02357 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02358                 const char *secret, const char *md5secret, int sipmethod,
02359                 char *uri, enum xmittype reliable, int ignore);
02360 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02361                      int sipmethod, char *uri, enum xmittype reliable,
02362                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02363 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02364 
02365 /*--- Domain handling */
02366 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02367 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02368 static void clear_sip_domains(void);
02369 
02370 /*--- SIP realm authentication */
02371 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02372 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02373 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02374 
02375 /*--- Misc functions */
02376 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02377 static int sip_do_reload(enum channelreloadreason reason);
02378 static int reload_config(enum channelreloadreason reason);
02379 static int expire_register(const void *data);
02380 static void *do_monitor(void *data);
02381 static int restart_monitor(void);
02382 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02383 static struct ast_variable *copy_vars(struct ast_variable *src);
02384 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02385 static int sip_refer_allocate(struct sip_pvt *p);
02386 static void ast_quiet_chan(struct ast_channel *chan);
02387 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02388 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
02389 
02390 /*!
02391  * \brief generic function for determining if a correct transport is being 
02392  * used to contact a peer
02393  *
02394  * this is done as a macro so that the "tmpl" var can be passed either a 
02395  * sip_request or a sip_peer 
02396  */
02397 #define check_request_transport(peer, tmpl) ({ \
02398    int ret = 0; \
02399    if (peer->socket.type == tmpl->socket.type) \
02400       ; \
02401    else if (!(peer->transports & tmpl->socket.type)) {\
02402       ast_log(LOG_ERROR, \
02403          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02404          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02405          ); \
02406       ret = 1; \
02407    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02408       ast_log(LOG_WARNING, \
02409          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02410          peer->name, get_transport(tmpl->socket.type) \
02411       ); \
02412    } else { \
02413       ast_debug(1, \
02414          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02415          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02416       ); \
02417    }\
02418    (ret); \
02419 })
02420 
02421 
02422 /*--- Device monitoring and Device/extension state/event handling */
02423 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02424 static int sip_devicestate(void *data);
02425 static int sip_poke_noanswer(const void *data);
02426 static int sip_poke_peer(struct sip_peer *peer, int force);
02427 static void sip_poke_all_peers(void);
02428 static void sip_peer_hold(struct sip_pvt *p, int hold);
02429 static void mwi_event_cb(const struct ast_event *, void *);
02430 
02431 /*--- Applications, functions, CLI and manager command helpers */
02432 static const char *sip_nat_mode(const struct sip_pvt *p);
02433 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02434 static char *transfermode2str(enum transfermodes mode) attribute_const;
02435 static const char *nat2str(int nat) attribute_const;
02436 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02437 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02438 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02439 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02440 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02441 static void  print_group(int fd, ast_group_t group, int crlf);
02442 static const char *dtmfmode2str(int mode) attribute_const;
02443 static int str2dtmfmode(const char *str) attribute_unused;
02444 static const char *insecure2str(int mode) attribute_const;
02445 static void cleanup_stale_contexts(char *new, char *old);
02446 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02447 static const char *domain_mode_to_text(const enum domain_mode mode);
02448 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02449 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02450 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02451 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02452 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02453 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02454 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02455 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02456 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02457 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02458 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02459 static char *complete_sip_peer(const char *word, int state, int flags2);
02460 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02461 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02462 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02463 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02464 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02465 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02466 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02467 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02468 static char *sip_do_debug_ip(int fd, char *arg);
02469 static char *sip_do_debug_peer(int fd, char *arg);
02470 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02471 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02472 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02473 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02474 static int sip_addheader(struct ast_channel *chan, void *data);
02475 static int sip_do_reload(enum channelreloadreason reason);
02476 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02477 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02478 
02479 /*--- Debugging 
02480    Functions for enabling debug per IP or fully, or enabling history logging for
02481    a SIP dialog
02482 */
02483 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02484 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02485 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02486 
02487 
02488 /*! \brief Append to SIP dialog history 
02489    \return Always returns 0 */
02490 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02491 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02492 static void sip_dump_history(struct sip_pvt *dialog);
02493 
02494 /*--- Device object handling */
02495 static struct sip_peer *temp_peer(const char *name);
02496 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02497 static int update_call_counter(struct sip_pvt *fup, int event);
02498 static void sip_destroy_peer(struct sip_peer *peer);
02499 static void sip_destroy_peer_fn(void *peer);
02500 static void set_peer_defaults(struct sip_peer *peer);
02501 static struct sip_peer *temp_peer(const char *name);
02502 static void register_peer_exten(struct sip_peer *peer, int onoff);
02503 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
02504 static int sip_poke_peer_s(const void *data);
02505 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02506 static void reg_source_db(struct sip_peer *peer);
02507 static void destroy_association(struct sip_peer *peer);
02508 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02509 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02510 static void set_socket_transport(struct sip_socket *socket, int transport);
02511 
02512 /* Realtime device support */
02513 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms);
02514 static void update_peer(struct sip_peer *p, int expire);
02515 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02516 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02517 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02518 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02519 
02520 /*--- Internal UA client handling (outbound registrations) */
02521 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02522 static void sip_registry_destroy(struct sip_registry *reg);
02523 static int sip_register(const char *value, int lineno);
02524 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02525 static int sip_reregister(const void *data);
02526 static int __sip_do_register(struct sip_registry *r);
02527 static int sip_reg_timeout(const void *data);
02528 static void sip_send_all_registers(void);
02529 static int sip_reinvite_retry(const void *data);
02530 
02531 /*--- Parsing SIP requests and responses */
02532 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02533 static int determine_firstline_parts(struct sip_request *req);
02534 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02535 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02536 static int find_sip_method(const char *msg);
02537 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02538 static int parse_request(struct sip_request *req);
02539 static const char *get_header(const struct sip_request *req, const char *name);
02540 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02541 static int method_match(enum sipmethod id, const char *name);
02542 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02543 static char *get_in_brackets(char *tmp);
02544 static const char *find_alias(const char *name, const char *_default);
02545 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02546 static int lws2sws(char *msgbuf, int len);
02547 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02548 static char *remove_uri_parameters(char *uri);
02549 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02550 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02551 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02552 static int set_address_from_contact(struct sip_pvt *pvt);
02553 static void check_via(struct sip_pvt *p, struct sip_request *req);
02554 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02555 static int get_rpid_num(const char *input, char *output, int maxlen);
02556 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02557 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02558 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02559 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02560 
02561 /*-- TCP connection handling ---*/
02562 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02563 static void *sip_tcp_worker_fn(void *);
02564 
02565 /*--- Constructing requests and responses */
02566 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02567 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02568 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02569 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02570 static int init_resp(struct sip_request *resp, const char *msg);
02571 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02572 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02573 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02574 static void build_via(struct sip_pvt *p);
02575 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02576 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02577 static char *generate_random_string(char *buf, size_t size);
02578 static void build_callid_pvt(struct sip_pvt *pvt);
02579 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02580 static void make_our_tag(char *tagbuf, size_t len);
02581 static int add_header(struct sip_request *req, const char *var, const char *value);
02582 static int add_header_contentLength(struct sip_request *req, int len);
02583 static int add_line(struct sip_request *req, const char *line);
02584 static int add_text(struct sip_request *req, const char *text);
02585 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02586 static int add_vidupdate(struct sip_request *req);
02587 static void add_route(struct sip_request *req, struct sip_route *route);
02588 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02589 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02590 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02591 static void set_destination(struct sip_pvt *p, char *uri);
02592 static void append_date(struct sip_request *req);
02593 static void build_contact(struct sip_pvt *p);
02594 static void build_rpid(struct sip_pvt *p);
02595 
02596 /*------Request handling functions */
02597 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02598 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
02599 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02600 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02601 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02602 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02603 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02604 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02605 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02606 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02607 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02608 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02609 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02610 
02611 /*------Response handling functions */
02612 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02613 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02614 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02615 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02616 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02617 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02618 
02619 /*----- RTP interface functions */
02620 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp,  struct ast_rtp *trtp, int codecs, int nat_active);
02621 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02622 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02623 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02624 static int sip_get_codec(struct ast_channel *chan);
02625 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02626 
02627 /*------ T38 Support --------- */
02628 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02629 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02630 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02631 static void change_t38_state(struct sip_pvt *p, int state);
02632 
02633 /*------ Session-Timers functions --------- */
02634 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02635 static int  proc_session_timer(const void *vp);
02636 static void stop_session_timer(struct sip_pvt *p);
02637 static void start_session_timer(struct sip_pvt *p);
02638 static void restart_session_timer(struct sip_pvt *p);
02639 static const char *strefresher2str(enum st_refresher r);
02640 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02641 static int parse_minse(const char *p_hdrval, int *const p_interval);
02642 static int st_get_se(struct sip_pvt *, int max);
02643 static enum st_refresher st_get_refresher(struct sip_pvt *);
02644 static enum st_mode st_get_mode(struct sip_pvt *);
02645 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02646 
02647 /*!--- SIP MWI Subscription support */
02648 static int sip_subscribe_mwi(const char *value, int lineno);
02649 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
02650 static void sip_send_all_mwi_subscriptions(void);
02651 static int sip_subscribe_mwi_do(const void *data);
02652 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
02653 
02654 /*! \brief Definition of this channel for PBX channel registration */
02655 static const struct ast_channel_tech sip_tech = {
02656    .type = "SIP",
02657    .description = "Session Initiation Protocol (SIP)",
02658    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02659    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02660    .requester = sip_request_call,         /* called with chan unlocked */
02661    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02662    .call = sip_call,       /* called with chan locked */
02663    .send_html = sip_sendhtml,
02664    .hangup = sip_hangup,         /* called with chan locked */
02665    .answer = sip_answer,         /* called with chan locked */
02666    .read = sip_read,       /* called with chan locked */
02667    .write = sip_write,        /* called with chan locked */
02668    .write_video = sip_write,     /* called with chan locked */
02669    .write_text = sip_write,
02670    .indicate = sip_indicate,     /* called with chan locked */
02671    .transfer = sip_transfer,     /* called with chan locked */
02672    .fixup = sip_fixup,        /* called with chan locked */
02673    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02674    .send_digit_end = sip_senddigit_end,
02675    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02676    .early_bridge = ast_rtp_early_bridge,
02677    .send_text = sip_sendtext,    /* called with chan locked */
02678    .func_channel_read = acf_channel_read,
02679    .queryoption = sip_queryoption,
02680    .get_pvt_uniqueid = sip_get_callid,
02681 };
02682 
02683 /*! \brief This version of the sip channel tech has no send_digit_begin
02684  * callback so that the core knows that the channel does not want
02685  * DTMF BEGIN frames.
02686  * The struct is initialized just before registering the channel driver,
02687  * and is for use with channels using SIP INFO DTMF.
02688  */
02689 static struct ast_channel_tech sip_tech_info;
02690 
02691 
02692 /*! \brief Working TLS connection configuration */
02693 static struct ast_tls_config sip_tls_cfg;
02694 
02695 /*! \brief Default TLS connection configuration */
02696 static struct ast_tls_config default_tls_cfg;
02697 
02698 /*! \brief The TCP server definition */
02699 static struct ast_tcptls_session_args sip_tcp_desc = {
02700    .accept_fd = -1,
02701    .master = AST_PTHREADT_NULL,
02702    .tls_cfg = NULL,
02703    .poll_timeout = -1,
02704    .name = "SIP TCP server",
02705    .accept_fn = ast_tcptls_server_root,
02706    .worker_fn = sip_tcp_worker_fn,
02707 };
02708 
02709 /*! \brief The TCP/TLS server definition */
02710 static struct ast_tcptls_session_args sip_tls_desc = {
02711    .accept_fd = -1,
02712    .master = AST_PTHREADT_NULL,
02713    .tls_cfg = &sip_tls_cfg,
02714    .poll_timeout = -1,
02715    .name = "SIP TLS server",
02716    .accept_fn = ast_tcptls_server_root,
02717    .worker_fn = sip_tcp_worker_fn,
02718 };
02719 
02720 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02721 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02722 
02723 /*! \brief map from an integer value to a string.
02724  * If no match is found, return errorstring
02725  */
02726 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02727 {
02728    const struct _map_x_s *cur;
02729 
02730    for (cur = table; cur->s; cur++)
02731       if (cur->x == x)
02732          return cur->s;
02733    return errorstring;
02734 }
02735 
02736 /*! \brief map from a string to an integer value, case insensitive.
02737  * If no match is found, return errorvalue.
02738  */
02739 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02740 {
02741    const struct _map_x_s *cur;
02742 
02743    for (cur = table; cur->s; cur++)
02744       if (!strcasecmp(cur->s, s))
02745          return cur->x;
02746    return errorvalue;
02747 }
02748 
02749 
02750 /*! \brief Interface structure with callbacks used to connect to RTP module */
02751 static struct ast_rtp_protocol sip_rtp = {
02752    .type = "SIP",
02753    .get_rtp_info = sip_get_rtp_peer,
02754    .get_vrtp_info = sip_get_vrtp_peer,
02755    .get_trtp_info = sip_get_trtp_peer,
02756    .set_rtp_peer = sip_set_rtp_peer,
02757    .get_codec = sip_get_codec,
02758 };
02759 
02760 /*!
02761  * duplicate a list of channel variables, \return the copy.
02762  */
02763 static struct ast_variable *copy_vars(struct ast_variable *src)
02764 {
02765    struct ast_variable *res = NULL, *tmp, *v = NULL;
02766 
02767    for (v = src ; v ; v = v->next) {
02768       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02769          tmp->next = res;
02770          res = tmp;
02771       }
02772    }
02773    return res;
02774 }
02775 
02776 static void tcptls_packet_destructor(void *obj)
02777 {
02778    struct tcptls_packet *packet = obj;
02779 
02780    ast_free(packet->data);
02781 }
02782 
02783 static void sip_tcptls_client_args_destructor(void *obj)
02784 {
02785    struct ast_tcptls_session_args *args = obj;
02786    if (args->tls_cfg) {
02787       ast_free(args->tls_cfg->certfile);
02788       ast_free(args->tls_cfg->cipher);
02789       ast_free(args->tls_cfg->cafile);
02790       ast_free(args->tls_cfg->capath);
02791    }
02792    ast_free(args->tls_cfg);
02793    ast_free((char *) args->name);
02794 }
02795 
02796 static void sip_threadinfo_destructor(void *obj)
02797 {
02798    struct sip_threadinfo *th = obj;
02799    struct tcptls_packet *packet;
02800    if (th->alert_pipe[1] > -1) {
02801       close(th->alert_pipe[0]);
02802    }
02803    if (th->alert_pipe[1] > -1) {
02804       close(th->alert_pipe[1]);
02805    }
02806    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02807 
02808    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02809       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02810    }
02811 
02812    if (th->tcptls_session) {
02813       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02814    }
02815 }
02816 
02817 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02818 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02819 {
02820    struct sip_threadinfo *th;
02821 
02822    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02823       return NULL;
02824    }
02825 
02826    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02827 
02828    if (pipe(th->alert_pipe) == -1) {
02829       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02830       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02831       return NULL;
02832    }
02833    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02834    th->tcptls_session = tcptls_session;
02835    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02836    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02837    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02838    return th;
02839 }
02840 
02841 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02842 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02843 {
02844    int res = len;
02845    struct sip_threadinfo *th = NULL;
02846    struct tcptls_packet *packet = NULL;
02847    struct sip_threadinfo tmp = {
02848       .tcptls_session = tcptls_session,
02849    };
02850    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02851 
02852    if (!tcptls_session) {
02853       return XMIT_ERROR;
02854    }
02855 
02856    ast_mutex_lock(&tcptls_session->lock);
02857 
02858    if ((tcptls_session->fd == -1) ||
02859       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02860       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02861       !(packet->data = ast_str_create(len))) {
02862       goto tcptls_write_setup_error;
02863    }
02864 
02865    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02866    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02867    packet->len = len;
02868 
02869    /* alert tcptls thread handler that there is a packet to be sent.
02870     * must lock the thread info object to guarantee control of the
02871     * packet queue */
02872    ao2_lock(th);
02873    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02874       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02875       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02876       packet = NULL;
02877       res = XMIT_ERROR;
02878    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02879       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02880    }
02881    ao2_unlock(th);
02882 
02883    ast_mutex_unlock(&tcptls_session->lock);
02884    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02885    return res;
02886 
02887 tcptls_write_setup_error:
02888    if (th) {
02889       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02890    }
02891    if (packet) {
02892       ao2_t_ref(packet, -1, "could not allocate packet's data");
02893    }
02894    ast_mutex_unlock(&tcptls_session->lock);
02895 
02896    return XMIT_ERROR;
02897 }
02898 
02899 /*! \brief SIP TCP connection handler */
02900 static void *sip_tcp_worker_fn(void *data)
02901 {
02902    struct ast_tcptls_session_instance *tcptls_session = data;
02903 
02904    return _sip_tcp_helper_thread(NULL, tcptls_session);
02905 }
02906 
02907 /*! \brief SIP TCP thread management function 
02908    This function reads from the socket, parses the packet into a request
02909 */
02910 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02911 {
02912    int res, cl;
02913    struct sip_request req = { 0, } , reqcpy = { 0, };
02914    struct sip_threadinfo *me = NULL;
02915    char buf[1024] = "";
02916    struct pollfd fds[2] = { { 0 }, { 0 }, };
02917    struct ast_tcptls_session_args *ca = NULL;
02918 
02919    /* If this is a server session, then the connection has already been setup,
02920     * simply create the threadinfo object so we can access this thread for writing.
02921     * 
02922     * if this is a client connection more work must be done.
02923     * 1. We own the parent session args for a client connection.  This pointer needs
02924     *    to be held on to so we can decrement it's ref count on thread destruction.
02925     * 2. The threadinfo object was created before this thread was launched, however
02926     *    it must be found within the threadt table.
02927     * 3. Last, the tcptls_session must be started.
02928     */
02929    if (!tcptls_session->client) {
02930       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02931          goto cleanup;
02932       }
02933       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02934    } else {
02935       struct sip_threadinfo tmp = {
02936          .tcptls_session = tcptls_session,
02937       };
02938 
02939       if ((!(ca = tcptls_session->parent)) ||
02940          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02941          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02942          goto cleanup;
02943       }
02944    }
02945 
02946    me->threadid = pthread_self();
02947    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02948 
02949    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02950    fds[0].fd = tcptls_session->fd;
02951    fds[1].fd = me->alert_pipe[0];
02952    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02953 
02954    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02955       goto cleanup;
02956    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02957       goto cleanup;
02958 
02959    for (;;) {
02960       struct ast_str *str_save;
02961 
02962       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02963 
02964       if (res < 0) {
02965          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02966          goto cleanup;
02967       }
02968 
02969       /* handle the socket event, check for both reads from the socket fd,
02970        * and writes from alert_pipe fd */
02971       if (fds[0].revents) { /* there is data on the socket to be read */
02972 
02973          fds[0].revents = 0;
02974 
02975          /* clear request structure */
02976          str_save = req.data;
02977          memset(&req, 0, sizeof(req));
02978          req.data = str_save;
02979          ast_str_reset(req.data);
02980 
02981          str_save = reqcpy.data;
02982          memset(&reqcpy, 0, sizeof(reqcpy));
02983          reqcpy.data = str_save;
02984          ast_str_reset(reqcpy.data);
02985 
02986          memset(buf, 0, sizeof(buf));
02987 
02988          if (tcptls_session->ssl) {
02989             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02990             req.socket.port = htons(ourport_tls);
02991          } else {
02992             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02993             req.socket.port = htons(ourport_tcp);
02994          }
02995          req.socket.fd = tcptls_session->fd;
02996 
02997          /* Read in headers one line at a time */
02998          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02999             ast_mutex_lock(&tcptls_session->lock);
03000             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
03001                ast_mutex_unlock(&tcptls_session->lock);
03002                goto cleanup;
03003             }
03004             ast_mutex_unlock(&tcptls_session->lock);
03005             if (me->stop)
03006                 goto cleanup;
03007             ast_str_append(&req.data, 0, "%s", buf);
03008             req.len = req.data->used;
03009          }
03010          copy_request(&reqcpy, &req);
03011          parse_request(&reqcpy);
03012          /* In order to know how much to read, we need the content-length header */
03013          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
03014             while (cl > 0) {
03015                size_t bytes_read;
03016                ast_mutex_lock(&tcptls_session->lock);
03017                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
03018                   ast_mutex_unlock(&tcptls_session->lock);
03019                   goto cleanup;
03020                }
03021                buf[bytes_read] = '\0';
03022                ast_mutex_unlock(&tcptls_session->lock);
03023                if (me->stop)
03024                   goto cleanup;
03025                cl -= strlen(buf);
03026                ast_str_append(&req.data, 0, "%s", buf);
03027                req.len = req.data->used;
03028             }
03029          }
03030          /*! \todo XXX If there's no Content-Length or if the content-length and what
03031                we receive is not the same - we should generate an error */
03032 
03033          req.socket.tcptls_session = tcptls_session;
03034          handle_request_do(&req, &tcptls_session->remote_address);
03035       }
03036 
03037       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03038          enum sip_tcptls_alert alert;
03039          struct tcptls_packet *packet;
03040 
03041          fds[1].revents = 0;
03042 
03043          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03044             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03045             continue;
03046          }
03047 
03048          switch (alert) {
03049          case TCPTLS_ALERT_STOP:
03050             goto cleanup;
03051          case TCPTLS_ALERT_DATA:
03052             ao2_lock(me);
03053             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03054                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
03055             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03056                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03057             }
03058 
03059             if (packet) {
03060                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03061             }
03062             ao2_unlock(me);
03063             break;
03064          default:
03065             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03066          }
03067       }
03068    }
03069 
03070    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
03071 
03072 cleanup:
03073    if (me) {
03074       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03075       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03076    }
03077    if (reqcpy.data) {
03078       ast_free(reqcpy.data);
03079    }
03080 
03081    if (req.data) {
03082       ast_free(req.data);
03083       req.data = NULL;
03084    }
03085 
03086    /* if client, we own the parent session arguments and must decrement ref */
03087    if (ca) {
03088       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03089    }
03090 
03091    if (tcptls_session) {
03092       ast_mutex_lock(&tcptls_session->lock);
03093       if (tcptls_session->f) {
03094          fclose(tcptls_session->f);
03095          tcptls_session->f = NULL;
03096       }
03097       if (tcptls_session->fd != -1) {
03098          close(tcptls_session->fd);
03099          tcptls_session->fd = -1;
03100       }
03101       tcptls_session->parent = NULL;
03102       ast_mutex_unlock(&tcptls_session->lock);
03103 
03104       ao2_ref(tcptls_session, -1);
03105       tcptls_session = NULL;
03106    }
03107    return NULL;
03108 }
03109 
03110 
03111 /*!
03112  * helper functions to unreference various types of objects.
03113  * By handling them this way, we don't have to declare the
03114  * destructor on each call, which removes the chance of errors.
03115  */
03116 static void *unref_peer(struct sip_peer *peer, char *tag)
03117 {
03118    ao2_t_ref(peer, -1, tag);
03119    return NULL;
03120 }
03121 
03122 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
03123 {
03124    ao2_t_ref(peer, 1, tag);
03125    return peer;
03126 }
03127 
03128 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03129  *
03130  * This function sets pvt's outboundproxy pointer to the one referenced
03131  * by the proxy parameter. Because proxy may be a refcounted object, and
03132  * because pvt's old outboundproxy may also be a refcounted object, we need
03133  * to maintain the proper refcounts.
03134  *
03135  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03136  * \param proxy The sip_proxy which we will point pvt towards.
03137  * \return Returns void
03138  */
03139 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03140 {
03141    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03142    /* The sip_cfg.outboundproxy is statically allocated, and so
03143     * we don't ever need to adjust refcounts for it
03144     */
03145    if (proxy && proxy != &sip_cfg.outboundproxy) {
03146       ao2_ref(proxy, +1);
03147    }
03148    pvt->outboundproxy = proxy;
03149    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03150       ao2_ref(old_obproxy, -1);
03151    }
03152 }
03153 
03154 /*!
03155  * \brief Unlink a dialog from the dialogs container, as well as any other places
03156  * that it may be currently stored.
03157  *
03158  * \note A reference to the dialog must be held before calling this function, and this
03159  * function does not release that reference.
03160  */
03161 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
03162 {
03163    struct sip_pkt *cp;
03164 
03165    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03166 
03167    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03168 
03169    /* Unlink us from the owner (channel) if we have one */
03170    if (dialog->owner) {
03171       if (lockowner)
03172          ast_channel_lock(dialog->owner);
03173       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
03174       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03175       if (lockowner)
03176          ast_channel_unlock(dialog->owner);
03177    }
03178    if (dialog->registry) {
03179       if (dialog->registry->call == dialog)
03180          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03181       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03182    }
03183    if (dialog->stateid > -1) {
03184       ast_extension_state_del(dialog->stateid, NULL);
03185       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
03186       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
03187    }
03188    /* Remove link from peer to subscription of MWI */
03189    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
03190       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03191    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
03192       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03193 
03194    /* remove all current packets in this dialog */
03195    while((cp = dialog->packets)) {
03196       dialog->packets = dialog->packets->next;
03197       AST_SCHED_DEL(sched, cp->retransid);
03198       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03199       if (cp->data) {
03200          ast_free(cp->data);
03201       }
03202       ast_free(cp);
03203    }
03204 
03205    AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
03206 
03207    AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
03208    
03209    if (dialog->autokillid > -1)
03210       AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
03211 
03212    if (dialog->request_queue_sched_id > -1) {
03213       AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
03214    }
03215 
03216    AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03217 
03218    if (dialog->t38id > -1) {
03219       AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
03220    }
03221 
03222    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03223    return NULL;
03224 }
03225 
03226 static void *registry_unref(struct sip_registry *reg, char *tag)
03227 {
03228    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03229    ASTOBJ_UNREF(reg, sip_registry_destroy);
03230    return NULL;
03231 }
03232 
03233 /*! \brief Add object reference to SIP registry */
03234 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03235 {
03236    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03237    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03238 }
03239 
03240 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03241 static struct ast_udptl_protocol sip_udptl = {
03242    type: "SIP",
03243    get_udptl_info: sip_get_udptl_peer,
03244    set_udptl_peer: sip_set_udptl_peer,
03245 };
03246 
03247 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03248    __attribute__((format(printf, 2, 3)));
03249 
03250 
03251 /*! \brief Convert transfer status to string */
03252 static const char *referstatus2str(enum referstatus rstatus)
03253 {
03254    return map_x_s(referstatusstrings, rstatus, "");
03255 }
03256 
03257 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03258 {
03259    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03260    pvt->needdestroy = 1;
03261 }
03262 
03263 /*! \brief Initialize the initital request packet in the pvt structure.
03264    This packet is used for creating replies and future requests in
03265    a dialog */
03266 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03267 {
03268    if (p->initreq.headers)
03269       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03270    else
03271       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03272    /* Use this as the basis */
03273    copy_request(&p->initreq, req);
03274    parse_request(&p->initreq);
03275    if (req->debug)
03276       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03277 }
03278 
03279 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03280 static void sip_alreadygone(struct sip_pvt *dialog)
03281 {
03282    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03283    dialog->alreadygone = 1;
03284 }
03285 
03286 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03287 static int proxy_update(struct sip_proxy *proxy)
03288 {
03289    /* if it's actually an IP address and not a name,
03290            there's no need for a managed lookup */
03291    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
03292       /* Ok, not an IP address, then let's check if it's a domain or host */
03293       /* XXX Todo - if we have proxy port, don't do SRV */
03294       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03295          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03296          return FALSE;
03297       }
03298    }
03299    proxy->last_dnsupdate = time(NULL);
03300    return TRUE;
03301 }
03302 
03303 /*! \brief converts ascii port to int representation. If no
03304  *  pt buffer is provided or the pt has errors when being converted
03305  *  to an int value, the port provided as the standard is used.
03306  */
03307 static int port_str2int(const char *pt, unsigned int standard)
03308 {
03309    int port = standard;
03310    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03311       port = standard;
03312    }
03313 
03314    return port;
03315 }
03316 
03317 /*! \brief Allocate and initialize sip proxy */
03318 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
03319 {
03320    struct sip_proxy *proxy;
03321 
03322    if (ast_strlen_zero(name)) {
03323       return NULL;
03324    }
03325 
03326    proxy = ao2_alloc(sizeof(*proxy), NULL);
03327    if (!proxy)
03328       return NULL;
03329    proxy->force = force;
03330    ast_copy_string(proxy->name, name, sizeof(proxy->name));
03331    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
03332    proxy_update(proxy);
03333    return proxy;
03334 }
03335 
03336 /*! \brief Get default outbound proxy or global proxy */
03337 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03338 {
03339    if (peer && peer->outboundproxy) {
03340       if (sipdebug)
03341          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03342       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03343       return peer->outboundproxy;
03344    }
03345    if (sip_cfg.outboundproxy.name[0]) {
03346       if (sipdebug)
03347          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03348       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03349       return &sip_cfg.outboundproxy;
03350    }
03351    if (sipdebug)
03352       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03353    return NULL;
03354 }
03355 
03356 /*! \brief returns true if 'name' (with optional trailing whitespace)
03357  * matches the sip method 'id'.
03358  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03359  * a case-insensitive comparison to be more tolerant.
03360  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03361  */
03362 static int method_match(enum sipmethod id, const char *name)
03363 {
03364    int len = strlen(sip_methods[id].text);
03365    int l_name = name ? strlen(name) : 0;
03366    /* true if the string is long enough, and ends with whitespace, and matches */
03367    return (l_name >= len && name[len] < 33 &&
03368       !strncasecmp(sip_methods[id].text, name, len));
03369 }
03370 
03371 /*! \brief  find_sip_method: Find SIP method from header */
03372 static int find_sip_method(const char *msg)
03373 {
03374    int i, res = 0;
03375    
03376    if (ast_strlen_zero(msg))
03377       return 0;
03378    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03379       if (method_match(i, msg))
03380          res = sip_methods[i].id;
03381    }
03382    return res;
03383 }
03384 
03385 /*! \brief Parse supported header in incoming packet */
03386 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03387 {
03388    char *next, *sep;
03389    char *temp;
03390    unsigned int profile = 0;
03391    int i, found;
03392 
03393    if (ast_strlen_zero(supported) )
03394       return 0;
03395    temp = ast_strdupa(supported);
03396 
03397    if (sipdebug)
03398       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03399 
03400    for (next = temp; next; next = sep) {
03401       found = FALSE;
03402       if ( (sep = strchr(next, ',')) != NULL)
03403          *sep++ = '\0';
03404       next = ast_skip_blanks(next);
03405       if (sipdebug)
03406          ast_debug(3, "Found SIP option: -%s-\n", next);
03407       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03408          if (!strcasecmp(next, sip_options[i].text)) {
03409             profile |= sip_options[i].id;
03410             found = TRUE;
03411             if (sipdebug)
03412                ast_debug(3, "Matched SIP option: %s\n", next);
03413             break;
03414          }
03415       }
03416 
03417       /* This function is used to parse both Suported: and Require: headers.
03418       Let the caller of this function know that an unknown option tag was 
03419       encountered, so that if the UAC requires it then the request can be 
03420       rejected with a 420 response. */
03421       if (!found)
03422          profile |= SIP_OPT_UNKNOWN;
03423 
03424       if (!found && sipdebug) {
03425          if (!strncasecmp(next, "x-", 2))
03426             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03427          else
03428             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03429       }
03430    }
03431 
03432    if (pvt)
03433       pvt->sipoptions = profile;
03434    return profile;
03435 }
03436 
03437 /*! \brief See if we pass debug IP filter */
03438 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03439 {
03440    if (!sipdebug)
03441       return 0;
03442    if (debugaddr.sin_addr.s_addr) {
03443       if (((ntohs(debugaddr.sin_port) != 0)
03444          && (debugaddr.sin_port != addr->sin_port))
03445          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03446          return 0;
03447    }
03448    return 1;
03449 }
03450 
03451 /*! \brief The real destination address for a write */
03452 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03453 {
03454    if (p->outboundproxy)
03455       return &p->outboundproxy->ip;
03456 
03457    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03458 }
03459 
03460 /*! \brief Display SIP nat mode */
03461 static const char *sip_nat_mode(const struct sip_pvt *p)
03462 {
03463    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03464 }
03465 
03466 /*! \brief Test PVT for debugging output */
03467 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03468 {
03469    if (!sipdebug)
03470       return 0;
03471    return sip_debug_test_addr(sip_real_dst(p));
03472 }
03473 
03474 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03475 static int get_transport_str2enum(const char *transport)
03476 {
03477    int res = 0;
03478 
03479    if (ast_strlen_zero(transport)) {
03480       return res;
03481    }
03482 
03483    if (!strcasecmp(transport, "udp")) {
03484       res |= SIP_TRANSPORT_UDP;
03485    }
03486    if (!strcasecmp(transport, "tcp")) {
03487       res |= SIP_TRANSPORT_TCP;
03488    }
03489    if (!strcasecmp(transport, "tls")) {
03490       res |= SIP_TRANSPORT_TLS;
03491    }
03492 
03493    return res;
03494 }
03495 
03496 /*! \brief Return configuration of transports for a device */
03497 static inline const char *get_transport_list(unsigned int transports) {
03498    switch (transports) {
03499       case SIP_TRANSPORT_UDP:
03500          return "UDP";
03501       case SIP_TRANSPORT_TCP:
03502          return "TCP";
03503       case SIP_TRANSPORT_TLS:
03504          return "TLS";
03505       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03506          return "TCP,UDP";
03507       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03508          return "TLS,UDP";
03509       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03510          return "TLS,TCP";
03511       default:
03512          return transports ? 
03513             "TLS,TCP,UDP" : "UNKNOWN"; 
03514    }
03515 }
03516 
03517 /*! \brief Return transport as string */
03518 static inline const char *get_transport(enum sip_transport t)
03519 {
03520    switch (t) {
03521    case SIP_TRANSPORT_UDP:
03522       return "UDP";
03523    case SIP_TRANSPORT_TCP:
03524       return "TCP";
03525    case SIP_TRANSPORT_TLS:
03526       return "TLS";
03527    }
03528 
03529    return "UNKNOWN";
03530 }
03531 
03532 /*! \brief Return transport of dialog.
03533    \note this is based on a false assumption. We don't always use the
03534    outbound proxy for all requests in a dialog. It depends on the
03535    "force" parameter. The FIRST request is always sent to the ob proxy.
03536    \todo Fix this function to work correctly
03537 */
03538 static inline const char *get_transport_pvt(struct sip_pvt *p)
03539 {
03540    if (p->outboundproxy && p->outboundproxy->transport) {
03541       set_socket_transport(&p->socket, p->outboundproxy->transport);
03542    }
03543 
03544    return get_transport(p->socket.type);
03545 }
03546 
03547 /*! \brief Transmit SIP message 
03548    Sends a SIP request or response on a given socket (in the pvt)
03549    Called by retrans_pkt, send_request, send_response and 
03550    __sip_reliable_xmit
03551 */
03552 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03553 {
03554    int res = 0;
03555    const struct sockaddr_in *dst = sip_real_dst(p);
03556 
03557    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
03558 
03559    if (sip_prepare_socket(p) < 0)
03560       return XMIT_ERROR;
03561 
03562    if (p->socket.type == SIP_TRANSPORT_UDP) {
03563       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03564    } else if (p->socket.tcptls_session) {
03565       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03566    } else {
03567       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03568       return XMIT_ERROR;
03569    }
03570 
03571    if (res == -1) {
03572       switch (errno) {
03573       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03574       case EHOSTUNREACH:   /* Host can't be reached */
03575       case ENETDOWN:       /* Inteface down */
03576       case ENETUNREACH: /* Network failure */
03577       case ECONNREFUSED:      /* ICMP port unreachable */ 
03578          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03579       }
03580    }
03581    if (res != len)
03582       ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
03583 
03584    return res;
03585 }
03586 
03587 /*! \brief Build a Via header for a request */
03588 static void build_via(struct sip_pvt *p)
03589 {
03590    /* Work around buggy UNIDEN UIP200 firmware */
03591    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03592 
03593    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03594    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03595        get_transport_pvt(p),
03596        ast_inet_ntoa(p->ourip.sin_addr),
03597        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03598 }
03599 
03600 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03601  *
03602  * Using the localaddr structure built up with localnet statements in sip.conf
03603  * apply it to their address to see if we need to substitute our
03604  * externip or can get away with our internal bindaddr
03605  * 'us' is always overwritten.
03606  */
03607 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03608 {
03609    struct sockaddr_in theirs;
03610    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03611     * reachable IP address and port. This is done if:
03612     * 1. we have a localaddr list (containing 'internal' addresses marked
03613     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03614     *    and AST_SENSE_ALLOW on 'external' ones);
03615     * 2. either stunaddr or externip is set, so we know what to use as the
03616     *    externally visible address;
03617     * 3. the remote address, 'them', is external;
03618     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03619     *    when passed to ast_apply_ha() so it does need to be remapped.
03620     *    This fourth condition is checked later.
03621     */
03622    int want_remap;
03623 
03624    *us = internip;      /* starting guess for the internal address */
03625    /* now ask the system what would it use to talk to 'them' */
03626    ast_ouraddrfor(them, &us->sin_addr);
03627    theirs.sin_addr = *them;
03628 
03629    want_remap = localaddr &&
03630       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03631       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03632 
03633    if (want_remap &&
03634        (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03635       /* if we used externhost or stun, see if it is time to refresh the info */
03636       if (externexpire && time(NULL) >= externexpire) {
03637          if (stunaddr.sin_addr.s_addr) {
03638             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03639          } else {
03640             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03641                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03642          }
03643          externexpire = time(NULL) + externrefresh;
03644       }
03645       if (externip.sin_addr.s_addr)
03646          *us = externip;
03647       else
03648          ast_log(LOG_WARNING, "stun failed\n");
03649       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03650          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03651    } else if (p) {
03652       /* no remapping, but we bind to a specific address, so use it. */
03653       switch (p->socket.type) {
03654       case SIP_TRANSPORT_TCP:
03655          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03656             *us = sip_tcp_desc.local_address;
03657          } else {
03658             us->sin_port = sip_tcp_desc.local_address.sin_port;
03659          }
03660          break;
03661       case SIP_TRANSPORT_TLS:
03662          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03663             *us = sip_tls_desc.local_address;
03664          } else {
03665             us->sin_port = sip_tls_desc.local_address.sin_port;
03666          }
03667             break;
03668       case SIP_TRANSPORT_UDP:
03669          /* fall through on purpose */
03670       default:
03671          if (bindaddr.sin_addr.s_addr) {
03672             *us = bindaddr;
03673          }
03674       }
03675    } else if (bindaddr.sin_addr.s_addr) {
03676       *us = bindaddr;
03677    }
03678    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
03679 }
03680 
03681 /*! \brief Append to SIP dialog history with arg list  */
03682 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03683 {
03684    char buf[80], *c = buf; /* max history length */
03685    struct sip_history *hist;
03686    int l;
03687 
03688    vsnprintf(buf, sizeof(buf), fmt, ap);
03689    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03690    l = strlen(buf) + 1;
03691    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03692       return;
03693    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03694       ast_free(hist);
03695       return;
03696    }
03697    memcpy(hist->event, buf, l);
03698    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03699       struct sip_history *oldest;
03700       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03701       p->history_entries--;
03702       ast_free(oldest);
03703    }
03704    AST_LIST_INSERT_TAIL(p->history, hist, list);
03705    p->history_entries++;
03706 }
03707 
03708 /*! \brief Append to SIP dialog history with arg list  */
03709 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03710 {
03711    va_list ap;
03712 
03713    if (!p)
03714       return;
03715 
03716    if (!p->do_history && !recordhistory && !dumphistory)
03717       return;
03718 
03719    va_start(ap, fmt);
03720    append_history_va(p, fmt, ap);
03721    va_end(ap);
03722 
03723    return;
03724 }
03725 
03726 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03727 static int retrans_pkt(const void *data)
03728 {
03729    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03730    int reschedule = DEFAULT_RETRANS;
03731    int xmitres = 0;
03732    
03733    /* Lock channel PVT */
03734    sip_pvt_lock(pkt->owner);
03735 
03736    if (pkt->retrans < MAX_RETRANS) {
03737       pkt->retrans++;
03738       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03739          if (sipdebug)
03740             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
03741       } else {
03742          int siptimer_a;
03743 
03744          if (sipdebug)
03745             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03746          if (!pkt->timer_a)
03747             pkt->timer_a = 2 ;
03748          else
03749             pkt->timer_a = 2 * pkt->timer_a;
03750  
03751          /* For non-invites, a maximum of 4 secs */
03752          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03753          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03754             siptimer_a = 4000;
03755       
03756          /* Reschedule re-transmit */
03757          reschedule = siptimer_a;
03758          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
03759       } 
03760 
03761       if (sip_debug_test_pvt(pkt->owner)) {
03762          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03763          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03764             pkt->retrans, sip_nat_mode(pkt->owner),
03765             ast_inet_ntoa(dst->sin_addr),
03766             ntohs(dst->sin_port), pkt->data->str);
03767       }
03768 
03769       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03770       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03771       sip_pvt_unlock(pkt->owner);
03772       if (xmitres == XMIT_ERROR)
03773          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03774       else 
03775          return  reschedule;
03776    } 
03777    /* Too many retries */
03778    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03779       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03780          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03781             pkt->owner->callid, pkt->seqno,
03782             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03783    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03784          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03785 
03786    } 
03787    if (xmitres == XMIT_ERROR) {
03788       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03789       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03790    } else 
03791       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03792       
03793    pkt->retransid = -1;
03794 
03795    if (pkt->is_fatal) {
03796       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03797          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03798          usleep(1);
03799          sip_pvt_lock(pkt->owner);
03800       }
03801 
03802       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03803          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03804       
03805       if (pkt->owner->owner) {
03806          sip_alreadygone(pkt->owner);
03807          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03808          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03809          ast_channel_unlock(pkt->owner->owner);
03810       } else {
03811          /* If no channel owner, destroy now */
03812 
03813          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03814          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03815             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03816             sip_alreadygone(pkt->owner);
03817             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03818          }
03819       }
03820    }
03821 
03822    if (pkt->method == SIP_BYE) {
03823       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03824       if (pkt->owner->owner) 
03825          ast_channel_unlock(pkt->owner->owner);
03826       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03827       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03828    }
03829 
03830    /* Remove the packet */
03831    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03832       if (cur == pkt) {
03833          UNLINK(cur, pkt->owner->packets, prev);
03834          sip_pvt_unlock(pkt->owner);
03835          if (pkt->owner)
03836             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03837          if (pkt->data)
03838             ast_free(pkt->data);
03839          pkt->data = NULL;
03840          ast_free(pkt);
03841          return 0;
03842       }
03843    }
03844    /* error case */
03845    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03846    sip_pvt_unlock(pkt->owner);
03847    return 0;
03848 }
03849 
03850 /*! \brief Transmit packet with retransmits 
03851    \return 0 on success, -1 on failure to allocate packet 
03852 */
03853 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
03854 {
03855    struct sip_pkt *pkt = NULL;
03856    int siptimer_a = DEFAULT_RETRANS;
03857    int xmitres = 0;
03858    int respid;
03859 
03860    if (sipmethod == SIP_INVITE) {
03861       /* Note this is a pending invite */
03862       p->pendinginvite = seqno;
03863    }
03864 
03865    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03866    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03867    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03868    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03869       xmitres = __sip_xmit(p, data, len); /* Send packet */
03870       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03871          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03872          return AST_FAILURE;
03873       } else {
03874          return AST_SUCCESS;
03875       }
03876    }
03877 
03878    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03879       return AST_FAILURE;
03880    /* copy data, add a terminator and save length */
03881    if (!(pkt->data = ast_str_create(len))) {
03882       ast_free(pkt);
03883       return AST_FAILURE;
03884    }
03885    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03886    pkt->packetlen = len;
03887    /* copy other parameters from the caller */
03888    pkt->method = sipmethod;
03889    pkt->seqno = seqno;
03890    pkt->is_resp = resp;
03891    pkt->is_fatal = fatal;
03892    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03893    pkt->next = p->packets;
03894    p->packets = pkt; /* Add it to the queue */
03895    if (resp) {
03896       /* Parse out the response code */
03897       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03898          pkt->response_code = respid;
03899       }
03900    }
03901    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03902    pkt->retransid = -1;
03903    if (pkt->timer_t1)
03904       siptimer_a = pkt->timer_t1 * 2;
03905 
03906    /* Schedule retransmission */
03907    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03908    if (sipdebug)
03909       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03910 
03911    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03912 
03913    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03914       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03915       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03916       AST_SCHED_DEL(sched, pkt->retransid);
03917       p->packets = pkt->next;
03918       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03919       ast_free(pkt->data);
03920       ast_free(pkt);
03921       return AST_FAILURE;
03922    } else {
03923       return AST_SUCCESS;
03924    }
03925 }
03926 
03927 /*! \brief Kill a SIP dialog (called only by the scheduler)
03928  * The scheduler has a reference to this dialog when p->autokillid != -1,
03929  * and we are called using that reference. So if the event is not
03930  * rescheduled, we need to call dialog_unref().
03931  */
03932 static int __sip_autodestruct(const void *data)
03933 {
03934    struct sip_pvt *p = (struct sip_pvt *)data;
03935 
03936    /* If this is a subscription, tell the phone that we got a timeout */
03937    if (p->subscribed) {
03938       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03939       p->subscribed = NONE;
03940       append_history(p, "Subscribestatus", "timeout");
03941       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03942       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03943    }
03944 
03945    /* If there are packets still waiting for delivery, delay the destruction */
03946    if (p->packets) {
03947       if (!p->needdestroy) {
03948          char method_str[31];
03949          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03950          append_history(p, "ReliableXmit", "timeout");
03951          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03952             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03953                pvt_set_needdestroy(p, "autodestruct");
03954             }
03955          }
03956          return 10000;
03957       } else {
03958          /* They've had their chance to respond. Time to bail */
03959          __sip_pretend_ack(p);
03960       }
03961    }
03962 
03963    if (p->subscribed == MWI_NOTIFICATION)
03964       if (p->relatedpeer)
03965          p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");   /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
03966 
03967    /* Reset schedule ID */
03968    p->autokillid = -1;
03969 
03970    if (p->owner) {
03971       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03972       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03973    } else if (p->refer && !p->alreadygone) {
03974       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03975       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03976       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03977       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03978    } else {
03979       append_history(p, "AutoDestroy", "%s", p->callid);
03980       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03981       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03982       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03983       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03984       /* sip_destroy also absorbs the reference */
03985    }
03986    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03987    return 0;
03988 }
03989 
03990 /*! \brief Schedule destruction of SIP dialog */
03991 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03992 {
03993    if (ms < 0) {
03994       if (p->timer_t1 == 0) {
03995          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03996          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03997       }
03998       ms = p->timer_t1 * 64;
03999    }
04000    if (sip_debug_test_pvt(p))
04001       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04002    if (sip_cancel_destroy(p))
04003       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04004 
04005    if (p->do_history)
04006       append_history(p, "SchedDestroy", "%d ms", ms);
04007    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04008 
04009    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
04010       stop_session_timer(p);
04011 }
04012 
04013 /*! \brief Cancel destruction of SIP dialog.
04014  * Be careful as this also absorbs the reference - if you call it
04015  * from within the scheduler, this might be the last reference.
04016  */
04017 static int sip_cancel_destroy(struct sip_pvt *p)
04018 {
04019    int res = 0;
04020    if (p->autokillid > -1) {
04021       int res3;
04022 
04023       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
04024          append_history(p, "CancelDestroy", "");
04025          p->autokillid = -1;
04026          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
04027       }
04028    }
04029    return res;
04030 }
04031 
04032 /*! \brief Acknowledges receipt of a packet and stops retransmission 
04033  * called with p locked*/
04034 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04035 {
04036    struct sip_pkt *cur, *prev = NULL;
04037    const char *msg = "Not Found";   /* used only for debugging */
04038    int res = FALSE;
04039 
04040    /* If we have an outbound proxy for this dialog, then delete it now since
04041      the rest of the requests in this dialog needs to follow the routing.
04042      If obforcing is set, we will keep the outbound proxy during the whole
04043      dialog, regardless of what the SIP rfc says
04044    */
04045    if (p->outboundproxy && !p->outboundproxy->force){
04046       ref_proxy(p, NULL);
04047    }
04048 
04049    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04050       if (cur->seqno != seqno || cur->is_resp != resp)
04051          continue;
04052       if (cur->is_resp || cur->method == sipmethod) {
04053          res = TRUE;
04054          msg = "Found";
04055          if (!resp && (seqno == p->pendinginvite)) {
04056             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
04057             p->pendinginvite = 0;
04058          }
04059          if (cur->retransid > -1) {
04060             if (sipdebug)
04061                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04062          }
04063          /* This odd section is designed to thwart a 
04064           * race condition in the packet scheduler. There are
04065           * two conditions under which deleting the packet from the
04066           * scheduler can fail.
04067           *
04068           * 1. The packet has been removed from the scheduler because retransmission
04069           * is being attempted. The problem is that if the packet is currently attempting
04070           * retransmission and we are at this point in the code, then that MUST mean
04071           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04072           * lock temporarily to allow retransmission.
04073           *
04074           * 2. The packet has reached its maximum number of retransmissions and has
04075           * been permanently removed from the packet scheduler. If this is the case, then
04076           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04077           * of the retransid to -1 is ensured since in both cases p's lock is held.
04078           */
04079          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04080             sip_pvt_unlock(p);
04081             usleep(1);
04082             sip_pvt_lock(p);
04083          }
04084          UNLINK(cur, p->packets, prev);
04085          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04086          if (cur->data)
04087             ast_free(cur->data);
04088          ast_free(cur);
04089          break;
04090       }
04091    }
04092    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
04093       p->callid, resp ? "Response" : "Request", seqno, msg);
04094    return res;
04095 }
04096 
04097 /*! \brief Pretend to ack all packets
04098  * called with p locked */
04099 static void __sip_pretend_ack(struct sip_pvt *p)
04100 {
04101    struct sip_pkt *cur = NULL;
04102 
04103    while (p->packets) {
04104       int method;
04105       if (cur == p->packets) {
04106          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04107          return;
04108       }
04109       cur = p->packets;
04110       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04111       __sip_ack(p, cur->seqno, cur->is_resp, method);
04112    }
04113 }
04114 
04115 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04116 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
04117 {
04118    struct sip_pkt *cur;
04119    int res = FALSE;
04120 
04121    for (cur = p->packets; cur; cur = cur->next) {
04122       if (cur->seqno == seqno && cur->is_resp == resp &&
04123          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04124          /* this is our baby */
04125          if (cur->retransid > -1) {
04126             if (sipdebug)
04127                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04128          }
04129          AST_SCHED_DEL(sched, cur->retransid);
04130          res = TRUE;
04131          break;
04132       }
04133    }
04134    ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04135    return res;
04136 }
04137 
04138 
04139 /*! \brief Copy SIP request, parse it */
04140 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04141 {
04142    copy_request(dst, src);
04143    parse_request(dst);
04144 }
04145 
04146 /*! \brief add a blank line if no body */
04147 static void add_blank(struct sip_request *req)
04148 {
04149    if (!req->lines) {
04150       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04151       ast_str_append(&req->data, 0, "\r\n");
04152       req->len = ast_str_strlen(req->data);
04153    }
04154 }
04155 
04156 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04157 {
04158    const char *msg = NULL;
04159 
04160    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04161       msg = "183 Session Progress";
04162    }
04163 
04164    if (pvt->invitestate < INV_COMPLETED) {
04165       if (with_sdp) {
04166          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
04167       } else {
04168          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04169       }
04170       return PROVIS_KEEPALIVE_TIMEOUT;
04171    }
04172 
04173    return 0;
04174 }
04175 
04176 static int send_provisional_keepalive(const void *data) {
04177    struct sip_pvt *pvt = (struct sip_pvt *) data;
04178 
04179    return send_provisional_keepalive_full(pvt, 0);
04180 }
04181 
04182 static int send_provisional_keepalive_with_sdp(const void *data) {
04183    struct sip_pvt *pvt = (void *)data;
04184 
04185    return send_provisional_keepalive_full(pvt, 1);
04186 }
04187 
04188 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04189 {
04190    AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
04191 
04192    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04193       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04194 }
04195 
04196 /*! \brief Transmit response on SIP request*/
04197 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04198 {
04199    int res;
04200 
04201    add_blank(req);
04202    if (sip_debug_test_pvt(p)) {
04203       const struct sockaddr_in *dst = sip_real_dst(p);
04204 
04205       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
04206          reliable ? "Reliably " : "", sip_nat_mode(p),
04207          ast_inet_ntoa(dst->sin_addr),
04208          ntohs(dst->sin_port), req->data->str);
04209    }
04210    if (p->do_history) {
04211       struct sip_request tmp = { .rlPart1 = 0, };
04212       parse_copy(&tmp, req);
04213       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
04214          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04215       ast_free(tmp.data);
04216    }
04217 
04218    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04219    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04220       AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
04221    }
04222 
04223    res = (reliable) ?
04224        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04225       __sip_xmit(p, req->data, req->len);
04226    ast_free(req->data);
04227    req->data = NULL;
04228    if (res > 0)
04229       return 0;
04230    return res;
04231 }
04232 
04233 /*! \brief Send SIP Request to the other part of the dialogue */
04234 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
04235 {
04236    int res;
04237 
04238    /* If we have an outbound proxy, reset peer address 
04239       Only do this once.
04240    */
04241    if (p->outboundproxy) {
04242       p->sa = p->outboundproxy->ip;
04243    }
04244 
04245    add_blank(req);
04246    if (sip_debug_test_pvt(p)) {
04247       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
04248          ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
04249       else
04250          ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
04251    }
04252    if (p->do_history) {
04253       struct sip_request tmp = { .rlPart1 = 0, };
04254       parse_copy(&tmp, req);
04255       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04256       ast_free(tmp.data);
04257    }
04258    res = (reliable) ?
04259       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
04260       __sip_xmit(p, req->data, req->len);
04261    if (req->data) {
04262       ast_free(req->data);
04263       req->data = NULL;
04264    }
04265    return res;
04266 }
04267 
04268 /*! \brief Query an option on a SIP dialog */
04269 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04270 {
04271    int res = -1;
04272    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04273    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04274 
04275    switch (option) {
04276    case AST_OPTION_T38_STATE:
04277       /* Make sure we got an ast_t38_state enum passed in */
04278       if (*datalen != sizeof(enum ast_t38_state)) {
04279          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04280          return -1;
04281       }
04282 
04283       sip_pvt_lock(p);
04284 
04285       /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
04286       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04287          switch (p->t38.state) {
04288          case T38_LOCAL_REINVITE:
04289          case T38_PEER_REINVITE:
04290             state = T38_STATE_NEGOTIATING;
04291             break;
04292          case T38_ENABLED:
04293             state = T38_STATE_NEGOTIATED;
04294             break;
04295          default:
04296             state = T38_STATE_UNKNOWN;
04297          }
04298       }
04299 
04300       sip_pvt_unlock(p);
04301 
04302       *((enum ast_t38_state *) data) = state;
04303       res = 0;
04304 
04305       break;
04306    default:
04307       break;
04308    }
04309 
04310    return res;
04311 }
04312 
04313 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04314  * optionally with a limit on the search.
04315  * start must be past the first quote.
04316  */
04317 static const char *find_closing_quote(const char *start, const char *lim)
04318 {
04319    char last_char = '\0';
04320    const char *s;
04321    for (s = start; *s && s != lim; last_char = *s++) {
04322       if (*s == '"' && last_char != '\\')
04323          break;
04324    }
04325    return s;
04326 }
04327 
04328 /*! \brief Pick out text in brackets from character string
04329    \return pointer to terminated stripped string
04330    \param tmp input string that will be modified
04331    Examples:
04332 \verbatim
04333    "foo" <bar> valid input, returns bar
04334    foo      returns the whole string
04335    < "foo ... >   returns the string between brackets
04336    < "foo...   bogus (missing closing bracket), returns the whole string
04337          XXX maybe should still skip the opening bracket
04338 \endverbatim
04339  */
04340 static char *get_in_brackets(char *tmp)
04341 {
04342    const char *parse = tmp;
04343    char *first_bracket;
04344 
04345    /*
04346     * Skip any quoted text until we find the part in brackets.
04347    * On any error give up and return the full string.
04348    */
04349    while ( (first_bracket = strchr(parse, '<')) ) {
04350       char *first_quote = strchr(parse, '"');
04351 
04352       if (!first_quote || first_quote > first_bracket)
04353          break; /* no need to look at quoted part */
04354       /* the bracket is within quotes, so ignore it */
04355       parse = find_closing_quote(first_quote + 1, NULL);
04356       if (!*parse) { /* not found, return full string ? */
04357          /* XXX or be robust and return in-bracket part ? */
04358          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
04359          break;
04360       }
04361       parse++;
04362    }
04363    if (first_bracket) {
04364       char *second_bracket = strchr(first_bracket + 1, '>');
04365       if (second_bracket) {
04366          *second_bracket = '\0';
04367          tmp = first_bracket + 1;
04368       } else {
04369          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
04370       }
04371    }
04372    
04373    return tmp;
04374 }
04375 
04376 /*! \brief * parses a URI in its components.
04377  *
04378  * \note 
04379  * - If scheme is specified, drop it from the top.
04380  * - If a component is not requested, do not split around it.
04381  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
04382  *
04383  * This means that if we don't have domain, we cannot split
04384  * name:pass and domain:port.
04385  * It is safe to call with ret_name, pass, domain, port
04386  * pointing all to the same place.
04387  * Init pointers to empty string so we never get NULL dereferencing.
04388  * Overwrites the string.
04389  * return 0 on success, other values on error.
04390  * \verbatim 
04391  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04392  * \endverbatim
04393  * 
04394  */
04395 static int parse_uri(char *uri, const char *scheme,
04396    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04397 {
04398    char *name = NULL;
04399    int error = 0;
04400 
04401    /* init field as required */
04402    if (pass)
04403       *pass = "";
04404    if (port)
04405       *port = "";
04406    if (scheme) {
04407       int l;
04408       char *scheme2 = ast_strdupa(scheme);
04409       char *cur = strsep(&scheme2, ",");
04410       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04411          l = strlen(cur);
04412          if (!strncasecmp(uri, cur, l)) {
04413             uri += l;
04414             break;
04415          }
04416       }
04417       if (ast_strlen_zero(cur)) {
04418          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04419          error = -1;
04420       }
04421    }
04422    if (transport) {
04423       char *t, *type = "";
04424       *transport = "";
04425       if ((t = strstr(uri, "transport="))) {
04426          strsep(&t, "=");
04427          if ((type = strsep(&t, ";"))) {
04428             *transport = type;
04429          }
04430       }
04431    }
04432 
04433    if (!domain) {
04434       /* if we don't want to split around domain, keep everything as a name,
04435        * so we need to do nothing here, except remember why.
04436        */
04437    } else {
04438       /* store the result in a temp. variable to avoid it being
04439        * overwritten if arguments point to the same place.
04440        */
04441       char *c, *dom = "";
04442 
04443       if ((c = strchr(uri, '@')) == NULL) {
04444          /* domain-only URI, according to the SIP RFC. */
04445          dom = uri;
04446          name = "";
04447       } else {
04448          *c++ = '\0';
04449          dom = c;
04450          name = uri;
04451       }
04452 
04453       /* Remove options in domain and name */
04454       dom = strsep(&dom, ";");
04455       name = strsep(&name, ";");
04456 
04457       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04458          *c++ = '\0';
04459          *port = c;
04460       }
04461       if (pass && (c = strchr(name, ':'))) { /* user:password */
04462          *c++ = '\0';
04463          *pass = c;
04464       }
04465       *domain = dom;
04466    }
04467    if (ret_name)  /* same as for domain, store the result only at the end */
04468       *ret_name = name;
04469    if (options)
04470       *options = uri ? uri : "";
04471 
04472    return error;
04473 }
04474 
04475 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04476 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04477 {
04478    struct sip_pvt *p = chan->tech_pvt;
04479 
04480    if (subclass != AST_HTML_URL)
04481       return -1;
04482 
04483    ast_string_field_build(p, url, "<%s>;mode=active", data);
04484 
04485    if (sip_debug_test_pvt(p))
04486       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04487 
04488    switch (chan->_state) {
04489    case AST_STATE_RING:
04490       transmit_response(p, "100 Trying", &p->initreq);
04491       break;
04492    case AST_STATE_RINGING:
04493       transmit_response(p, "180 Ringing", &p->initreq);
04494       break;
04495    case AST_STATE_UP:
04496       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04497          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04498       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04499          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04500       }  
04501       break;
04502    default:
04503       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04504    }
04505 
04506    return 0;
04507 }
04508 
04509 /*! \brief Deliver SIP call ID for the call */
04510 static const char *sip_get_callid(struct ast_channel *chan)
04511 {
04512    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04513 }
04514 
04515 /*! \brief Send SIP MESSAGE text within a call
04516    Called from PBX core sendtext() application */
04517 static int sip_sendtext(struct ast_channel *ast, const char *text)
04518 {
04519    struct sip_pvt *p = ast->tech_pvt;
04520    int debug = sip_debug_test_pvt(p);
04521 
04522    if (debug)
04523       ast_verbose("Sending text %s on %s\n", text, ast->name);
04524    if (!p)
04525       return -1;
04526    /* NOT ast_strlen_zero, because a zero-length message is specifically
04527     * allowed by RFC 3428 (See section 10, Examples) */
04528    if (!text)
04529       return 0;
04530    if (debug)
04531       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04532    transmit_message_with_text(p, text);
04533    return 0;   
04534 }
04535 
04536 /*! \brief Update peer object in realtime storage 
04537    If the Asterisk system name is set in asterisk.conf, we will use
04538    that name and store that in the "regserver" field in the sippeers
04539    table to facilitate multi-server setups.
04540 */
04541 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, int deprecated_username, int lastms)
04542 {
04543    char port[10];
04544    char ipaddr[INET_ADDRSTRLEN];
04545    char regseconds[20];
04546    char *tablename = NULL;
04547    char str_lastms[20];
04548 
04549    const char *sysname = ast_config_AST_SYSTEM_NAME;
04550    char *syslabel = NULL;
04551 
04552    time_t nowtime = time(NULL) + expirey;
04553    const char *fc = fullcontact ? "fullcontact" : NULL;
04554 
04555    int realtimeregs = ast_check_realtime("sipregs");
04556 
04557    tablename = realtimeregs ? "sipregs" : "sippeers";
04558    
04559 
04560    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04561    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04562    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04563    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04564    
04565    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04566       sysname = NULL;
04567    else if (sip_cfg.rtsave_sysname)
04568       syslabel = "regserver";
04569 
04570    if (fc) {
04571       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04572          "port", port, "regseconds", regseconds,
04573          deprecated_username ? "username" : "defaultuser", defaultuser,
04574          "useragent", useragent, "lastms", str_lastms,
04575          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04576    } else {
04577       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04578          "port", port, "regseconds", regseconds,
04579          "useragent", useragent, "lastms", str_lastms,
04580          deprecated_username ? "username" : "defaultuser", defaultuser,
04581          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04582    }
04583 }
04584 
04585 /*! \brief Automatically add peer extension to dial plan */
04586 static void register_peer_exten(struct sip_peer *peer, int onoff)
04587 {
04588    char multi[256];
04589    char *stringp, *ext, *context;
04590    struct pbx_find_info q = { .stacklen = 0 };
04591 
04592    /* XXX note that global_regcontext is both a global 'enable' flag and
04593     * the name of the global regexten context, if not specified
04594     * individually.
04595     */
04596    if (ast_strlen_zero(global_regcontext))
04597       return;
04598 
04599    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04600    stringp = multi;
04601    while ((ext = strsep(&stringp, "&"))) {
04602       if ((context = strchr(ext, '@'))) {
04603          *context++ = '\0';   /* split ext@context */
04604          if (!ast_context_find(context)) {
04605             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04606             continue;
04607          }
04608       } else {
04609          context = global_regcontext;
04610       }
04611       if (onoff) {
04612          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04613             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04614                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04615          }
04616       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04617          ast_context_remove_extension(context, ext, 1, NULL);
04618       }
04619    }
04620 }
04621 
04622 /*! Destroy mailbox subscriptions */
04623 static void destroy_mailbox(struct sip_mailbox *mailbox)
04624 {
04625    if (mailbox->mailbox)
04626       ast_free(mailbox->mailbox);
04627    if (mailbox->context)
04628       ast_free(mailbox->context);
04629    if (mailbox->event_sub)
04630       ast_event_unsubscribe(mailbox->event_sub);
04631    ast_free(mailbox);
04632 }
04633 
04634 /*! Destroy all peer-related mailbox subscriptions */
04635 static void clear_peer_mailboxes(struct sip_peer *peer)
04636 {
04637    struct sip_mailbox *mailbox;
04638 
04639    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04640       destroy_mailbox(mailbox);
04641 }
04642 
04643 static void sip_destroy_peer_fn(void *peer)
04644 {
04645    sip_destroy_peer(peer);
04646 }
04647 
04648 /*! \brief Destroy peer object from memory */
04649 static void sip_destroy_peer(struct sip_peer *peer)
04650 {
04651    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04652    if (peer->outboundproxy)
04653       ao2_ref(peer->outboundproxy, -1);
04654    peer->outboundproxy = NULL;
04655 
04656    /* Delete it, it needs to disappear */
04657    if (peer->call) {
04658       dialog_unlink_all(peer->call, TRUE, TRUE);
04659       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04660    }
04661    
04662 
04663    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04664       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04665       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04666    }
04667    
04668    if (peer->chanvars) {
04669       ast_variables_destroy(peer->chanvars);
04670       peer->chanvars = NULL;
04671    }
04672    
04673    register_peer_exten(peer, FALSE);
04674    ast_free_ha(peer->ha);
04675    if (peer->selfdestruct)
04676       ast_atomic_fetchadd_int(&apeerobjs, -1);
04677    else if (peer->is_realtime) {
04678       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04679       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04680    } else
04681       ast_atomic_fetchadd_int(&speerobjs, -1);
04682    clear_realm_authentication(peer->auth);
04683    peer->auth = NULL;
04684    if (peer->dnsmgr)
04685       ast_dnsmgr_release(peer->dnsmgr);
04686    clear_peer_mailboxes(peer);
04687 
04688    if (peer->socket.tcptls_session) {
04689       ao2_ref(peer->socket.tcptls_session, -1);
04690       peer->socket.tcptls_session = NULL;
04691    }
04692 
04693    ast_string_field_free_memory(peer);
04694 }
04695 
04696 /*! \brief Update peer data in database (if used) */
04697 static void update_peer(struct sip_peer *p, int expire)
04698 {
04699    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04700    if (sip_cfg.peer_rtupdate &&
04701        (p->is_realtime || rtcachefriends)) {
04702       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04703    }
04704 }
04705 
04706 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04707 {
04708    struct ast_variable *var = NULL;
04709    struct ast_flags flags = {0};
04710    char *cat = NULL;
04711    const char *insecure;
04712    while ((cat = ast_category_browse(cfg, cat))) {
04713       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04714       set_insecure_flags(&flags, insecure, -1);
04715       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04716          var = ast_category_root(cfg, cat);
04717          break;
04718       }
04719    }
04720    return var;
04721 }
04722 
04723 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04724 {
04725    struct ast_variable *tmp;
04726    for (tmp = var; tmp; tmp = tmp->next) {
04727       if (!newpeername && !strcasecmp(tmp->name, "name"))
04728          newpeername = tmp->value;
04729    }
04730    return newpeername;
04731 }
04732 
04733 /*! \brief  realtime_peer: Get peer from realtime storage
04734  * Checks the "sippeers" realtime family from extconfig.conf 
04735  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04736  * This returns a pointer to a peer and because we use build_peer, we can rest
04737  * assured that the refcount is bumped.
04738 */
04739 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04740 {
04741    struct sip_peer *peer;
04742    struct ast_variable *var = NULL;
04743    struct ast_variable *varregs = NULL;
04744    struct ast_variable *tmp;
04745    struct ast_config *peerlist = NULL;
04746    char ipaddr[INET_ADDRSTRLEN];
04747    char portstring[6]; /*up to 5 digits plus null terminator*/
04748    char *cat = NULL;
04749    unsigned short portnum;
04750    int realtimeregs = ast_check_realtime("sipregs");
04751 
04752    /* First check on peer name */
04753    if (newpeername) {
04754       if (realtimeregs)
04755          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04756 
04757       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04758       if (!var && sin)
04759          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04760       if (!var) {
04761          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04762          /*!\note
04763           * If this one loaded something, then we need to ensure that the host
04764           * field matched.  The only reason why we can't have this as a criteria
04765           * is because we only have the IP address and the host field might be
04766           * set as a name (and the reverse PTR might not match).
04767           */
04768          if (var && sin) {
04769             for (tmp = var; tmp; tmp = tmp->next) {
04770                if (!strcasecmp(tmp->name, "host")) {
04771                   struct hostent *hp;
04772                   struct ast_hostent ahp;
04773                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04774                      /* No match */
04775                      ast_variables_destroy(var);
04776                      var = NULL;
04777                   }
04778                   break;
04779                }
04780             }
04781          }
04782       }
04783    }
04784 
04785    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04786       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04787       portnum = ntohs(sin->sin_port);
04788       sprintf(portstring, "%u", portnum);
04789       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04790       if (var) {
04791          if (realtimeregs) {
04792             newpeername = get_name_from_variable(var, newpeername);
04793             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04794          }
04795       } else {
04796          if (realtimeregs)
04797             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04798          else
04799             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04800          if (varregs) {
04801             newpeername = get_name_from_variable(varregs, newpeername);
04802             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04803          }
04804       }
04805       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04806          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04807          if (peerlist) {
04808             var = get_insecure_variable_from_config(peerlist);
04809             if(var) {
04810                if (realtimeregs) {
04811                   newpeername = get_name_from_variable(var, newpeername);
04812                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04813                }
04814             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04815                peerlist = NULL;
04816                cat = NULL;
04817                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04818                if(peerlist) {
04819                   var = get_insecure_variable_from_config(peerlist);
04820                   if(var) {
04821                      if (realtimeregs) {
04822                         newpeername = get_name_from_variable(var, newpeername);
04823                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04824                      }
04825                   }
04826                }
04827             }
04828          } else {
04829             if (realtimeregs) {
04830                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04831                if (peerlist) {
04832                   varregs = get_insecure_variable_from_config(peerlist);
04833                   if (varregs) {
04834                      newpeername = get_name_from_variable(varregs, newpeername);
04835                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04836                   }
04837                }
04838             } else {
04839                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04840                if (peerlist) {
04841                   var = get_insecure_variable_from_config(peerlist);
04842                   if (var) {
04843                      newpeername = get_name_from_variable(var, newpeername);
04844                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04845                   }
04846                }
04847             }
04848          }
04849       }
04850    }
04851 
04852    if (!var) {
04853       if (peerlist)
04854          ast_config_destroy(peerlist);
04855       return NULL;
04856    }
04857 
04858    for (tmp = var; tmp; tmp = tmp->next) {
04859       /* If this is type=user, then skip this object. */
04860       if (!strcasecmp(tmp->name, "type") &&
04861           !strcasecmp(tmp->value, "user")) {
04862          if(peerlist)
04863             ast_config_destroy(peerlist);
04864          else {
04865             ast_variables_destroy(var);
04866             ast_variables_destroy(varregs);
04867          }
04868          return NULL;
04869       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04870          newpeername = tmp->value;
04871       }
04872    }
04873    
04874    if (!newpeername) {  /* Did not find peer in realtime */
04875       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04876       if(peerlist)
04877          ast_config_destroy(peerlist);
04878       else
04879          ast_variables_destroy(var);
04880       return NULL;
04881    }
04882 
04883 
04884    /* Peer found in realtime, now build it in memory */
04885    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04886    if (!peer) {
04887       if(peerlist)
04888          ast_config_destroy(peerlist);
04889       else {
04890          ast_variables_destroy(var);
04891          ast_variables_destroy(varregs);
04892       }
04893       return NULL;
04894    }
04895 
04896    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04897 
04898    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04899       /* Cache peer */
04900       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04901       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04902          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
04903                unref_peer(_data, "remove registration ref"),
04904                unref_peer(peer, "remove registration ref"),
04905                ref_peer(peer, "add registration ref"));
04906       }
04907       ao2_t_link(peers, peer, "link peer into peers table");
04908       if (peer->addr.sin_addr.s_addr) {
04909          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04910       }
04911    }
04912    peer->is_realtime = 1;
04913    if (peerlist)
04914       ast_config_destroy(peerlist);
04915    else {
04916       ast_variables_destroy(var);
04917       ast_variables_destroy(varregs);
04918    }
04919 
04920    return peer;
04921 }
04922 
04923 /* Function to assist finding peers by name only */
04924 static int find_by_name(void *obj, void *arg, void *data, int flags)
04925 {
04926    struct sip_peer *search = obj, *match = arg;
04927    int *which_objects = data;
04928 
04929    /* Usernames in SIP uri's are case sensitive. Domains are not */
04930    if (strcmp(search->name, match->name)) {
04931       return 0;
04932    }
04933 
04934    switch (*which_objects) {
04935    case FINDUSERS:
04936       if (!(search->type & SIP_TYPE_USER)) {
04937          return 0;
04938       }
04939       break;
04940    case FINDPEERS:
04941       if (!(search->type & SIP_TYPE_PEER)) {
04942          return 0;
04943       }
04944       break;
04945    case FINDALLDEVICES:
04946       break;
04947    }
04948 
04949    return CMP_MATCH | CMP_STOP;
04950 }
04951 
04952 /*! 
04953  * \brief Locate device by name or ip address 
04954  *
04955  * \param which_objects Define which objects should be matched when doing a lookup
04956  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04957  *        Note that this option is not used at all when doing a lookup by IP.
04958  *
04959  * This is used on find matching device on name or ip/port.
04960  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04961  *
04962  * \note Avoid using this function in new functions if there is a way to avoid it,
04963  * since it might cause a database lookup.
04964  */
04965 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04966 {
04967    struct sip_peer *p = NULL;
04968    struct sip_peer tmp_peer;
04969 
04970    if (peer) {
04971       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
04972       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
04973    } else if (sin) { /* search by addr? */
04974       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04975       tmp_peer.addr.sin_port = sin->sin_port;
04976       tmp_peer.flags[0].flags = 0;
04977       tmp_peer.transports = transport;
04978       p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
04979       if (!p) {
04980          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04981          p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
04982          if (p) {
04983             return p;
04984          }
04985       }
04986    }
04987 
04988    if (!p && (realtime || devstate_only)) {
04989       p = realtime_peer(peer, sin, devstate_only);
04990    }
04991 
04992    return p;
04993 }
04994 
04995 /*! \brief Set nat mode on the various data sockets */
04996 static void do_setnat(struct sip_pvt *p, int natflags)
04997 {
04998    const char *mode = natflags ? "On" : "Off";
04999 
05000    if (p->rtp) {
05001       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05002       ast_rtp_setnat(p->rtp, natflags);
05003    }
05004    if (p->vrtp) {
05005       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05006       ast_rtp_setnat(p->vrtp, natflags);
05007    }
05008    if (p->udptl) {
05009       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05010       ast_udptl_setnat(p->udptl, natflags);
05011    }
05012    if (p->trtp) {
05013       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05014       ast_rtp_setnat(p->trtp, natflags);
05015    }
05016 }
05017 
05018 /*! \brief Change the T38 state on a SIP dialog */
05019 static void change_t38_state(struct sip_pvt *p, int state)
05020 {
05021    int old = p->t38.state;
05022    struct ast_channel *chan = p->owner;
05023    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05024 
05025    /* Don't bother changing if we are already in the state wanted */
05026    if (old == state)
05027       return;
05028 
05029    p->t38.state = state;
05030    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05031 
05032    /* If no channel was provided we can't send off a control frame */
05033    if (!chan)
05034       return;
05035 
05036    /* Given the state requested and old state determine what control frame we want to queue up */
05037    switch (state) {
05038    case T38_PEER_REINVITE:
05039       parameters = p->t38.their_parms;
05040       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05041       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05042       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05043       break;
05044    case T38_ENABLED:
05045       parameters = p->t38.their_parms;
05046       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05047       parameters.request_response = AST_T38_NEGOTIATED;
05048       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
05049       break;
05050    case T38_DISABLED:
05051       if (old == T38_ENABLED) {
05052          parameters.request_response = AST_T38_TERMINATED;
05053       } else if (old == T38_LOCAL_REINVITE) {
05054          parameters.request_response = AST_T38_REFUSED;
05055       }
05056       break;
05057    case T38_LOCAL_REINVITE:
05058       /* wait until we get a peer response before responding to local reinvite */
05059       break;
05060    }
05061 
05062    /* Woot we got a message, create a control frame and send it on! */
05063    if (parameters.request_response)
05064       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05065 }
05066 
05067 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05068 static void set_t38_capabilities(struct sip_pvt *p)
05069 {
05070    if (p->udptl) {
05071       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05072                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05073       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05074          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05075       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05076          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05077       }
05078    }
05079 }
05080 
05081 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05082 {
05083    if (to_sock->tcptls_session) {
05084       ao2_ref(to_sock->tcptls_session, -1);
05085       to_sock->tcptls_session = NULL;
05086    }
05087 
05088    if (from_sock->tcptls_session) {
05089       ao2_ref(from_sock->tcptls_session, +1);
05090    }
05091 
05092    *to_sock = *from_sock;
05093 }
05094 
05095 /*! \brief Create address structure from peer reference.
05096  * This function copies data from peer to the dialog, so we don't have to look up the peer
05097  * again from memory or database during the life time of the dialog.
05098  *
05099  * \return -1 on error, 0 on success.
05100  *
05101  */
05102 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05103 {
05104 
05105    /* this checks that the dialog is contacting the peer on a valid
05106     * transport type based on the peers transport configuration,
05107     * otherwise, this function bails out */
05108    if (dialog->socket.type && check_request_transport(peer, dialog))
05109       return -1;
05110    copy_socket_data(&dialog->socket, &peer->socket);
05111 
05112    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
05113        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05114       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
05115       dialog->recv = dialog->sa;
05116    } else 
05117       return -1;
05118 
05119    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05120    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05121    dialog->capability = peer->capability;
05122    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
05123          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
05124             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
05125          dialog->vrtp) {
05126       ast_rtp_destroy(dialog->vrtp);
05127       dialog->vrtp = NULL;
05128    }
05129    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
05130       ast_rtp_destroy(dialog->trtp);
05131       dialog->trtp = NULL;
05132    }
05133    dialog->prefs = peer->prefs;
05134    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
05135       if (!dialog->udptl) {
05136          /* t38pt_udptl was enabled in the peer and not in [general] */
05137          dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
05138       }
05139       dialog->t38_maxdatagram = peer->t38_maxdatagram;
05140       set_t38_capabilities(dialog);
05141    } else if (dialog->udptl) {
05142       ast_udptl_destroy(dialog->udptl);
05143       dialog->udptl = NULL;
05144    }
05145    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05146 
05147    if (dialog->rtp) { /* Audio */
05148       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05149       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05150       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
05151       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
05152       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
05153       if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
05154          ast_rtp_set_constantssrc(dialog->rtp);
05155       }
05156       /* Set Frame packetization */
05157       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
05158       dialog->autoframing = peer->autoframing;
05159    }
05160    if (dialog->vrtp) { /* Video */
05161       ast_rtp_setdtmf(dialog->vrtp, 0);
05162       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
05163       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
05164       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
05165       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
05166       if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
05167          ast_rtp_set_constantssrc(dialog->vrtp);
05168       }
05169    }
05170    if (dialog->trtp) { /* Realtime text */
05171       ast_rtp_setdtmf(dialog->trtp, 0);
05172       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
05173       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
05174       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
05175       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
05176    }
05177 
05178    ast_string_field_set(dialog, peername, peer->name);
05179    ast_string_field_set(dialog, authname, peer->username);
05180    ast_string_field_set(dialog, username, peer->username);
05181    ast_string_field_set(dialog, peersecret, peer->secret);
05182    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05183    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05184    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05185    ast_string_field_set(dialog, tohost, peer->tohost);
05186    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05187    ast_string_field_set(dialog, context, peer->context);
05188    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05189    ref_proxy(dialog, obproxy_get(dialog, peer));
05190    dialog->callgroup = peer->callgroup;
05191    dialog->pickupgroup = peer->pickupgroup;
05192    dialog->allowtransfer = peer->allowtransfer;
05193    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05194    dialog->rtptimeout = peer->rtptimeout;
05195    dialog->peerauth = peer->auth;
05196    dialog->maxcallbitrate = peer->maxcallbitrate;
05197    if (ast_strlen_zero(dialog->tohost))
05198       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
05199    if (!ast_strlen_zero(peer->fromdomain)) {
05200       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05201       if (!dialog->initreq.headers) {
05202          char *c;
05203          char *tmpcall = ast_strdupa(dialog->callid);
05204          /* this sure looks to me like we are going to change the callid on this dialog!! */
05205          c = strchr(tmpcall, '@');
05206          if (c) {
05207             *c = '\0';
05208             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
05209             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
05210             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
05211          }
05212       }
05213    }
05214    if (!ast_strlen_zero(peer->fromuser)) 
05215       ast_string_field_set(dialog, fromuser, peer->fromuser);
05216    if (!ast_strlen_zero(peer->language))
05217       ast_string_field_set(dialog, language, peer->language);
05218    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05219    /* Minimum is settable or default to 100 ms */
05220    /* If there is a maxms and lastms from a qualify use that over a manual T1
05221       value. Otherwise, use the peer's T1 value. */
05222    if (peer->maxms && peer->lastms)
05223       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05224    else
05225       dialog->timer_t1 = peer->timer_t1;
05226 
05227    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05228       the known timer */
05229    if (peer->timer_b)
05230       dialog->timer_b = peer->timer_b;
05231    else
05232       dialog->timer_b = 64 * dialog->timer_t1;
05233 
05234    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05235        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05236       dialog->noncodeccapability |= AST_RTP_DTMF;
05237    else
05238       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05239    if (peer->call_limit)
05240       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05241    if (!dialog->portinuri)
05242       dialog->portinuri = peer->portinuri;
05243    
05244    dialog->chanvars = copy_vars(peer->chanvars);
05245 
05246    return 0;
05247 }
05248 
05249 /*! \brief create address structure from device name
05250  *      Or, if peer not found, find it in the global DNS 
05251  *      returns TRUE (-1) on failure, FALSE on success */
05252 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
05253 {
05254    struct hostent *hp;
05255    struct ast_hostent ahp;
05256    struct sip_peer *peer;
05257    char *port;
05258    int portno = 0;
05259    char host[MAXHOSTNAMELEN], *hostn;
05260    char peername[256];
05261    int srv_ret = 0;
05262 
05263    ast_copy_string(peername, opeer, sizeof(peername));
05264    port = strchr(peername, ':');
05265    if (port) {
05266       *port++ = '\0';
05267       dialog->portinuri = 1;
05268    }
05269    dialog->sa.sin_family = AF_INET;
05270    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05271    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05272    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05273 
05274    if (peer) {
05275       int res;
05276       if (newdialog) {
05277          set_socket_transport(&dialog->socket, 0);
05278       }
05279       res = create_addr_from_peer(dialog, peer);
05280       if (!ast_strlen_zero(port)) {
05281          if ((portno = atoi(port))) {
05282             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
05283          }
05284       }
05285       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05286       return res;
05287    }
05288 
05289    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
05290 
05291    ast_string_field_set(dialog, tohost, peername);
05292 
05293    /* Get the outbound proxy information */
05294    ref_proxy(dialog, obproxy_get(dialog, NULL));
05295 
05296    if (sin) {
05297       /* This address should be updated using dnsmgr */
05298       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
05299       if (!sin->sin_port) {
05300          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05301       } else {
05302          portno = ntohs(sin->sin_port);
05303       }
05304    } else {
05305 
05306       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05307          then hostname lookup */
05308       /*! \todo Fix this function. When we ask for SRV, we should check all transports 
05309            In the future, we should first check NAPTR to find out transport preference
05310        */
05311       hostn = peername;
05312       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05313        * an A record lookup should be used instead of SRV.
05314        */
05315       if (!port && sip_cfg.srvlookup) {
05316          char service[MAXHOSTNAMELEN];
05317          int tportno;
05318    
05319          snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
05320          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
05321          if (srv_ret > 0) {
05322             hostn = host;
05323             portno = tportno;
05324          }
05325       }
05326       if (!portno)
05327          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
05328       hp = ast_gethostbyname(hostn, &ahp);
05329       if (!hp) {
05330          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05331          return -1;
05332       }
05333       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
05334    }
05335 
05336    if (!dialog->socket.type)
05337       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05338    if (!dialog->socket.port)
05339       dialog->socket.port = bindaddr.sin_port;
05340    dialog->sa.sin_port = htons(portno);
05341    dialog->recv = dialog->sa;
05342    return 0;
05343 }
05344 
05345 /*! \brief Scheduled congestion on a call.
05346  * Only called by the scheduler, must return the reference when done.
05347  */
05348 static int auto_congest(const void *arg)
05349 {
05350    struct sip_pvt *p = (struct sip_pvt *)arg;
05351 
05352    sip_pvt_lock(p);
05353    p->initid = -1;   /* event gone, will not be rescheduled */
05354    if (p->owner) {
05355       /* XXX fails on possible deadlock */
05356       if (!ast_channel_trylock(p->owner)) {
05357          append_history(p, "Cong", "Auto-congesting (timer)");
05358          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05359          ast_channel_unlock(p->owner);
05360       }
05361 
05362       /* Give the channel a chance to act before we proceed with destruction */
05363       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05364    }
05365    sip_pvt_unlock(p);
05366    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05367    return 0;
05368 }
05369 
05370 
05371 /*! \brief Initiate SIP call from PBX 
05372  *      used from the dial() application      */
05373 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05374 {
05375    int res;
05376    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05377    struct varshead *headp;
05378    struct ast_var_t *current;
05379    const char *referer = NULL;   /* SIP referrer */
05380 
05381    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05382       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05383       return -1;
05384    }
05385 
05386    /* Check whether there is vxml_url, distinctive ring variables */
05387    headp=&ast->varshead;
05388    AST_LIST_TRAVERSE(headp, current, entries) {
05389       /* Check whether there is a VXML_URL variable */
05390       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05391          p->options->vxml_url = ast_var_value(current);
05392       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05393          p->options->uri_options = ast_var_value(current);
05394       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05395          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05396          p->options->addsipheaders = 1;
05397       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05398          ast_string_field_set(p, fromdomain, ast_var_value(current));
05399       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05400          /* This is a transfered call */
05401          p->options->transfer = 1;
05402       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05403          /* This is the referrer */
05404          referer = ast_var_value(current);
05405       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05406          /* We're replacing a call. */
05407          p->options->replaces = ast_var_value(current);
05408       }
05409    }
05410 
05411    res = 0;
05412    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05413 
05414    if (p->options->transfer) {
05415       char buf[SIPBUFSIZE/2];
05416 
05417       if (referer) {
05418          if (sipdebug)
05419             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05420          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05421       } else 
05422          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05423       ast_string_field_set(p, cid_name, buf);
05424    } 
05425    ast_debug(1, "Outgoing Call for %s\n", p->username);
05426 
05427    res = update_call_counter(p, INC_CALL_RINGING);
05428 
05429    if (res == -1) {
05430       ast->hangupcause = AST_CAUSE_USER_BUSY;
05431       return res;
05432    }
05433    p->callingpres = ast->cid.cid_pres;
05434    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05435    p->jointnoncodeccapability = p->noncodeccapability;
05436 
05437    /* If there are no audio formats left to offer, punt */
05438    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05439       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05440       res = -1;
05441    } else {
05442       int xmitres;
05443 
05444       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05445       if (xmitres == XMIT_ERROR)
05446          return -1;
05447       p->invitestate = INV_CALLING;
05448    
05449       /* Initialize auto-congest time */
05450       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05451                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05452                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05453                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05454    }
05455    return res;
05456 }
05457 
05458 /*! \brief Destroy registry object
05459    Objects created with the register= statement in static configuration */
05460 static void sip_registry_destroy(struct sip_registry *reg)
05461 {
05462    /* Really delete */
05463    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05464 
05465    if (reg->call) {
05466       /* Clear registry before destroying to ensure
05467          we don't get reentered trying to grab the registry lock */
05468       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05469       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05470       dialog_unlink_all(reg->call, TRUE, TRUE);
05471       reg->call = dialog_unref(reg->call, "unref reg->call");
05472       /* reg->call = sip_destroy(reg->call); */
05473    }
05474    AST_SCHED_DEL(sched, reg->expire);  
05475    AST_SCHED_DEL(sched, reg->timeout);
05476    
05477    ast_string_field_free_memory(reg);
05478    ast_atomic_fetchadd_int(&regobjs, -1);
05479    ast_dnsmgr_release(reg->dnsmgr);
05480    ast_free(reg);
05481 }
05482 
05483 /*! \brief Destroy MWI subscription object */
05484 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05485 {
05486    if (mwi->call) {
05487       mwi->call->mwi = NULL;
05488       sip_destroy(mwi->call);
05489    }
05490    
05491    AST_SCHED_DEL(sched, mwi->resub);
05492    ast_string_field_free_memory(mwi);
05493    ast_dnsmgr_release(mwi->dnsmgr);
05494    ast_free(mwi);
05495 }
05496 
05497 /*! \brief Execute destruction of SIP dialog structure, release memory */
05498 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05499 {
05500    struct sip_request *req;
05501 
05502    if (p->stimer) {
05503       ast_free(p->stimer);
05504       p->stimer = NULL;
05505    }
05506 
05507    if (sip_debug_test_pvt(p))
05508       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05509 
05510    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05511       update_call_counter(p, DEC_CALL_LIMIT);
05512       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05513    }
05514 
05515    /* Unlink us from the owner if we have one */
05516    if (p->owner) {
05517       if (lockowner)
05518          ast_channel_lock(p->owner);
05519       if (option_debug)
05520          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05521       p->owner->tech_pvt = NULL;
05522       /* Make sure that the channel knows its backend is going away */
05523       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05524       if (lockowner)
05525          ast_channel_unlock(p->owner);
05526       /* Give the channel a chance to react before deallocation */
05527       usleep(1);
05528    }
05529 
05530    /* Remove link from peer to subscription of MWI */
05531    if (p->relatedpeer && p->relatedpeer->mwipvt)
05532       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05533    if (p->relatedpeer && p->relatedpeer->call == p)
05534       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05535    
05536    if (p->relatedpeer)
05537       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05538    
05539    if (p->registry) {
05540       if (p->registry->call == p)
05541          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05542       p->registry = registry_unref(p->registry, "delete p->registry");
05543    }
05544    
05545    if (p->mwi) {
05546       p->mwi->call = NULL;
05547    }
05548 
05549    if (dumphistory)
05550       sip_dump_history(p);
05551 
05552    if (p->options)
05553       ast_free(p->options);
05554 
05555    if (p->notify_headers) {
05556       ast_variables_destroy(p->notify_headers);
05557       p->notify_headers = NULL;
05558    }
05559    if (p->rtp) {
05560       ast_rtp_destroy(p->rtp);
05561    }
05562    if (p->vrtp) {
05563       ast_rtp_destroy(p->vrtp);
05564    }
05565    if (p->trtp) {
05566       while (ast_rtp_get_bridged(p->trtp))
05567          usleep(1);
05568       ast_rtp_destroy(p->trtp);
05569    }
05570    if (p->udptl)
05571       ast_udptl_destroy(p->udptl);
05572    if (p->refer)
05573       ast_free(p->refer);
05574    if (p->route) {
05575       free_old_route(p->route);
05576       p->route = NULL;
05577    }
05578    if (p->initreq.data)
05579       ast_free(p->initreq.data);
05580 
05581    /* Destroy Session-Timers if allocated */
05582    if (p->stimer) {
05583       p->stimer->quit_flag = 1;
05584       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05585          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05586                dialog_unref(p, "removing session timer ref"));
05587       }
05588       ast_free(p->stimer);
05589       p->stimer = NULL;
05590    }
05591 
05592    /* Clear history */
05593    if (p->history) {
05594       struct sip_history *hist;
05595       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05596          ast_free(hist);
05597          p->history_entries--;
05598       }
05599       ast_free(p->history);
05600       p->history = NULL;
05601    }
05602 
05603    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05604       ast_free(req);
05605    }
05606 
05607    if (p->chanvars) {
05608       ast_variables_destroy(p->chanvars);
05609       p->chanvars = NULL;
05610    }
05611 
05612    ast_string_field_free_memory(p);
05613 
05614    if (p->socket.tcptls_session) {
05615       ao2_ref(p->socket.tcptls_session, -1);
05616       p->socket.tcptls_session = NULL;
05617    }
05618 }
05619 
05620 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05621  * Setting a call-limit will cause calls above the limit not to be accepted.
05622  *
05623  * Remember that for a type=friend, there's one limit for the user and
05624  * another for the peer, not a combined call limit.
05625  * This will cause unexpected behaviour in subscriptions, since a "friend"
05626  * is *two* devices in Asterisk, not one.
05627  *
05628  * Thought: For realtime, we should probably update storage with inuse counter... 
05629  *
05630  * \return 0 if call is ok (no call limit, below threshold)
05631  * -1 on rejection of call
05632  *    
05633  */
05634 static int update_call_counter(struct sip_pvt *fup, int event)
05635 {
05636    char name[256];
05637    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05638    int outgoing = fup->outgoing_call;
05639    struct sip_peer *p = NULL;
05640 
05641    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05642 
05643 
05644    /* Test if we need to check call limits, in order to avoid 
05645       realtime lookups if we do not need it */
05646    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05647       return 0;
05648 
05649    ast_copy_string(name, fup->username, sizeof(name));
05650 
05651    /* Check the list of devices */
05652    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { 
05653       inuse = &p->inUse;
05654       call_limit = &p->call_limit;
05655       inringing = &p->inRinging;
05656       ast_copy_string(name, fup->peername, sizeof(name));
05657    }
05658    if (!p) {
05659       ast_debug(2, "%s is not a local device, no call limit\n", name);
05660       return 0;
05661    }
05662 
05663    switch(event) {
05664    /* incoming and outgoing affects the inUse counter */
05665    case DEC_CALL_LIMIT:
05666       /* Decrement inuse count if applicable */
05667       if (inuse) {
05668          sip_pvt_lock(fup);
05669          ao2_lock(p);
05670          if (*inuse > 0) {
05671             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05672                (*inuse)--;
05673                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05674             }
05675          } else {
05676             *inuse = 0;
05677          }
05678          ao2_unlock(p);
05679          sip_pvt_unlock(fup);
05680       }
05681 
05682       /* Decrement ringing count if applicable */
05683       if (inringing) {
05684          sip_pvt_lock(fup);
05685          ao2_lock(p);
05686          if (*inringing > 0) {
05687             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05688                (*inringing)--;
05689                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05690             }
05691          } else {
05692             *inringing = 0;
05693          }
05694          ao2_unlock(p);
05695          sip_pvt_unlock(fup);
05696       }
05697 
05698       /* Decrement onhold count if applicable */
05699       sip_pvt_lock(fup);
05700       ao2_lock(p);
05701       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
05702          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05703          ao2_unlock(p);
05704          sip_pvt_unlock(fup);
05705          sip_peer_hold(fup, FALSE);
05706       } else {
05707          ao2_unlock(p);
05708          sip_pvt_unlock(fup);
05709       }
05710       if (sipdebug)
05711          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05712       break;
05713 
05714    case INC_CALL_RINGING:
05715    case INC_CALL_LIMIT:
05716       /* If call limit is active and we have reached the limit, reject the call */
05717       if (*call_limit > 0 ) {
05718          if (*inuse >= *call_limit) {
05719             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05720             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05721             return -1; 
05722          }
05723       }
05724       if (inringing && (event == INC_CALL_RINGING)) {
05725          sip_pvt_lock(fup);
05726          ao2_lock(p);
05727          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05728             (*inringing)++;
05729             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05730          }
05731          ao2_unlock(p);
05732          sip_pvt_unlock(fup);
05733       }
05734       if (inuse) {
05735          sip_pvt_lock(fup);
05736          ao2_lock(p);
05737          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05738             (*inuse)++;
05739             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05740          }
05741          ao2_unlock(p);
05742          sip_pvt_unlock(fup);
05743       }
05744       if (sipdebug) {
05745          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05746       }
05747       break;
05748 
05749    case DEC_CALL_RINGING:
05750       if (inringing) {
05751          sip_pvt_lock(fup);
05752          ao2_lock(p);
05753          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05754             if (*inringing > 0) {
05755                (*inringing)--;
05756             }
05757             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05758          }
05759          ao2_unlock(p);
05760          sip_pvt_unlock(fup);
05761       }
05762       break;
05763 
05764    default:
05765       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05766    }
05767 
05768    if (p) {
05769       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05770       unref_peer(p, "update_call_counter: unref_peer from call counter");
05771    } 
05772    return 0;
05773 }
05774 
05775 
05776 static void sip_destroy_fn(void *p)
05777 {
05778    sip_destroy(p);
05779 }
05780 
05781 /*! \brief Destroy SIP call structure.
05782  * Make it return NULL so the caller can do things like
05783  * foo = sip_destroy(foo);
05784  * and reduce the chance of bugs due to dangling pointers.
05785  */
05786 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05787 {
05788    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05789    __sip_destroy(p, TRUE, TRUE);
05790    return NULL;
05791 }
05792 
05793 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05794 static int hangup_sip2cause(int cause)
05795 {
05796    /* Possible values taken from causes.h */
05797 
05798    switch(cause) {
05799       case 401:   /* Unauthorized */
05800          return AST_CAUSE_CALL_REJECTED;
05801       case 403:   /* Not found */
05802          return AST_CAUSE_CALL_REJECTED;
05803       case 404:   /* Not found */
05804          return AST_CAUSE_UNALLOCATED;
05805       case 405:   /* Method not allowed */
05806          return AST_CAUSE_INTERWORKING;
05807       case 407:   /* Proxy authentication required */
05808          return AST_CAUSE_CALL_REJECTED;
05809       case 408:   /* No reaction */
05810          return AST_CAUSE_NO_USER_RESPONSE;
05811       case 409:   /* Conflict */
05812          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05813       case 410:   /* Gone */
05814          return AST_CAUSE_NUMBER_CHANGED;
05815       case 411:   /* Length required */
05816          return AST_CAUSE_INTERWORKING;
05817       case 413:   /* Request entity too large */
05818          return AST_CAUSE_INTERWORKING;
05819       case 414:   /* Request URI too large */
05820          return AST_CAUSE_INTERWORKING;
05821       case 415:   /* Unsupported media type */
05822          return AST_CAUSE_INTERWORKING;
05823       case 420:   /* Bad extension */
05824          return AST_CAUSE_NO_ROUTE_DESTINATION;
05825       case 480:   /* No answer */
05826          return AST_CAUSE_NO_ANSWER;
05827       case 481:   /* No answer */
05828          return AST_CAUSE_INTERWORKING;
05829       case 482:   /* Loop detected */
05830          return AST_CAUSE_INTERWORKING;
05831       case 483:   /* Too many hops */
05832          return AST_CAUSE_NO_ANSWER;
05833       case 484:   /* Address incomplete */
05834          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05835       case 485:   /* Ambiguous */
05836          return AST_CAUSE_UNALLOCATED;
05837       case 486:   /* Busy everywhere */
05838          return AST_CAUSE_BUSY;
05839       case 487:   /* Request terminated */
05840          return AST_CAUSE_INTERWORKING;
05841       case 488:   /* No codecs approved */
05842          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05843       case 491:   /* Request pending */
05844          return AST_CAUSE_INTERWORKING;
05845       case 493:   /* Undecipherable */
05846          return AST_CAUSE_INTERWORKING;
05847       case 500:   /* Server internal failure */
05848          return AST_CAUSE_FAILURE;
05849       case 501:   /* Call rejected */
05850          return AST_CAUSE_FACILITY_REJECTED;
05851       case 502:   
05852          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05853       case 503:   /* Service unavailable */
05854          return AST_CAUSE_CONGESTION;
05855       case 504:   /* Gateway timeout */
05856          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05857       case 505:   /* SIP version not supported */
05858          return AST_CAUSE_INTERWORKING;
05859       case 600:   /* Busy everywhere */
05860          return AST_CAUSE_USER_BUSY;
05861       case 603:   /* Decline */
05862          return AST_CAUSE_CALL_REJECTED;
05863       case 604:   /* Does not exist anywhere */
05864          return AST_CAUSE_UNALLOCATED;
05865       case 606:   /* Not acceptable */
05866          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05867       default:
05868          return AST_CAUSE_NORMAL;
05869    }
05870    /* Never reached */
05871    return 0;
05872 }
05873 
05874 /*! \brief Convert Asterisk hangup causes to SIP codes 
05875 \verbatim
05876  Possible values from causes.h
05877         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05878         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05879 
05880    In addition to these, a lot of PRI codes is defined in causes.h 
05881    ...should we take care of them too ?
05882    
05883    Quote RFC 3398
05884 
05885    ISUP Cause value                        SIP response
05886    ----------------                        ------------
05887    1  unallocated number                   404 Not Found
05888    2  no route to network                  404 Not found
05889    3  no route to destination              404 Not found
05890    16 normal call clearing                 --- (*)
05891    17 user busy                            486 Busy here
05892    18 no user responding                   408 Request Timeout
05893    19 no answer from the user              480 Temporarily unavailable
05894    20 subscriber absent                    480 Temporarily unavailable
05895    21 call rejected                        403 Forbidden (+)
05896    22 number changed (w/o diagnostic)      410 Gone
05897    22 number changed (w/ diagnostic)       301 Moved Permanently
05898    23 redirection to new destination       410 Gone
05899    26 non-selected user clearing           404 Not Found (=)
05900    27 destination out of order             502 Bad Gateway
05901    28 address incomplete                   484 Address incomplete
05902    29 facility rejected                    501 Not implemented
05903    31 normal unspecified                   480 Temporarily unavailable
05904 \endverbatim
05905 */
05906 static const char *hangup_cause2sip(int cause)
05907 {
05908    switch (cause) {
05909       case AST_CAUSE_UNALLOCATED:      /* 1 */
05910       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05911       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05912          return "404 Not Found";
05913       case AST_CAUSE_CONGESTION:    /* 34 */
05914       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05915          return "503 Service Unavailable";
05916       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05917          return "408 Request Timeout";
05918       case AST_CAUSE_NO_ANSWER:     /* 19 */
05919       case AST_CAUSE_UNREGISTERED:        /* 20 */
05920          return "480 Temporarily unavailable";
05921       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05922          return "403 Forbidden";
05923       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05924          return "410 Gone";
05925       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05926          return "480 Temporarily unavailable";
05927       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05928          return "484 Address incomplete";
05929       case AST_CAUSE_USER_BUSY:
05930          return "486 Busy here";
05931       case AST_CAUSE_FAILURE:
05932          return "500 Server internal failure";
05933       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05934          return "501 Not Implemented";
05935       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05936          return "503 Service Unavailable";
05937       /* Used in chan_iax2 */
05938       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05939          return "502 Bad Gateway";
05940       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05941          return "488 Not Acceptable Here";
05942          
05943       case AST_CAUSE_NOTDEFINED:
05944       default:
05945          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05946          return NULL;
05947    }
05948 
05949    /* Never reached */
05950    return 0;
05951 }
05952 
05953 
05954 /*! \brief  sip_hangup: Hangup SIP call
05955  * Part of PBX interface, called from ast_hangup */
05956 static int sip_hangup(struct ast_channel *ast)
05957 {
05958    struct sip_pvt *p = ast->tech_pvt;
05959    int needcancel = FALSE;
05960    int needdestroy = 0;
05961    struct ast_channel *oldowner = ast;
05962 
05963    if (!p) {
05964       ast_debug(1, "Asked to hangup channel that was not connected\n");
05965       return 0;
05966    }
05967    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05968       ast_debug(1, "This call was answered elsewhere");
05969       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
05970          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
05971       }
05972       append_history(p, "Cancel", "Call answered elsewhere");
05973       p->answered_elsewhere = TRUE;
05974    }
05975 
05976    /* Store hangupcause locally in PVT so we still have it before disconnect */
05977    if (p->owner)
05978       p->hangupcause = p->owner->hangupcause;
05979 
05980    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05981       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05982          if (sipdebug)
05983             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05984          update_call_counter(p, DEC_CALL_LIMIT);
05985       }
05986       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05987       if (p->autokillid > -1 && sip_cancel_destroy(p))
05988          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05989       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05990       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05991       p->needdestroy = 0;
05992       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05993       sip_pvt_lock(p);
05994       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05995       sip_pvt_unlock(p);
05996       return 0;
05997    }
05998 
05999    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
06000       if (p->refer)
06001          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
06002       else
06003          ast_debug(1, "Hanging up zombie call. Be scared.\n");
06004    } else
06005       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06006 
06007    sip_pvt_lock(p);
06008    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06009       if (sipdebug)
06010          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06011       update_call_counter(p, DEC_CALL_LIMIT);
06012    }
06013 
06014    /* Determine how to disconnect */
06015    if (p->owner != ast) {
06016       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06017       sip_pvt_unlock(p);
06018       return 0;
06019    }
06020    /* If the call is not UP, we need to send CANCEL instead of BYE */
06021    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06022    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06023       needcancel = TRUE;
06024       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06025    }
06026 
06027    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06028 
06029    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06030 
06031    /* Disconnect */
06032    if (p->dsp)
06033       ast_dsp_free(p->dsp);
06034 
06035    p->owner = NULL;
06036    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06037 
06038    ast_module_unref(ast_module_info->self);
06039    /* Do not destroy this pvt until we have timeout or
06040       get an answer to the BYE or INVITE/CANCEL 
06041       If we get no answer during retransmit period, drop the call anyway.
06042       (Sorry, mother-in-law, you can't deny a hangup by sending
06043       603 declined to BYE...)
06044    */
06045    if (p->alreadygone)
06046       needdestroy = 1;  /* Set destroy flag at end of this function */
06047    else if (p->invitestate != INV_CALLING)
06048       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06049 
06050    /* Start the process if it's not already started */
06051    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06052       if (needcancel) { /* Outgoing call, not up */
06053          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06054             /* stop retransmitting an INVITE that has not received a response */
06055             /* if we can't send right now, mark it pending */
06056             if (p->invitestate == INV_CALLING) {
06057                /* We can't send anything in CALLING state */
06058                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06059                __sip_pretend_ack(p);
06060                /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
06061                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06062                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06063             } else {
06064                struct sip_pkt *cur;
06065 
06066                for (cur = p->packets; cur; cur = cur->next) {
06067                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06068                }
06069                p->invitestate = INV_CANCELLED;
06070                /* Send a new request: CANCEL */
06071                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06072                /* Actually don't destroy us yet, wait for the 487 on our original 
06073                   INVITE, but do set an autodestruct just in case we never get it. */
06074                needdestroy = 0;
06075                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06076             }
06077          } else { /* Incoming call, not up */
06078             const char *res;
06079             AST_SCHED_DEL(sched, p->provisional_keepalive_sched_id);
06080             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06081                transmit_response_reliable(p, res, &p->initreq);
06082             else 
06083                transmit_response_reliable(p, "603 Declined", &p->initreq);
06084             p->invitestate = INV_TERMINATED;
06085          }
06086       } else { /* Call is in UP state, send BYE */
06087          if (p->stimer->st_active == TRUE) {
06088             stop_session_timer(p);
06089          }
06090 
06091          if (!p->pendinginvite) {
06092             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06093             char *audioqos = "";
06094             char *videoqos = "";
06095             char *textqos = "";
06096 
06097             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
06098              * to lock the bridge. This may get hairy...
06099              */
06100             while (bridge && ast_channel_trylock(bridge)) {
06101                sip_pvt_unlock(p);
06102                do {
06103                   /* Use oldowner since p->owner is already NULL */
06104                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06105                } while (sip_pvt_trylock(p));
06106                bridge = ast_bridged_channel(oldowner);
06107             }
06108 
06109             if (p->rtp)
06110                ast_rtp_set_vars(oldowner, p->rtp);
06111 
06112             if (bridge) {
06113                struct sip_pvt *q = bridge->tech_pvt;
06114 
06115                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
06116                   ast_rtp_set_vars(bridge, q->rtp);
06117                ast_channel_unlock(bridge);
06118             }
06119 
06120             if (p->vrtp)
06121                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
06122             if (p->trtp)
06123                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
06124             /* Send a hangup */
06125             if (oldowner->_state == AST_STATE_UP) {
06126                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06127             }
06128 
06129             /* Get RTCP quality before end of call */
06130             if (p->do_history) {
06131                if (p->rtp)
06132                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
06133                if (p->vrtp)
06134                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
06135                if (p->trtp)
06136                   append_history(p, "RTCPtext", "Quality:%s", textqos);
06137             }
06138             if (p->rtp && oldowner)
06139                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
06140             if (p->vrtp && oldowner)
06141                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
06142             if (p->trtp && oldowner)
06143                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
06144          } else {
06145             /* Note we will need a BYE when this all settles out
06146                but we can't send one while we have "INVITE" outstanding. */
06147             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06148             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06149             AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
06150             if (sip_cancel_destroy(p))
06151                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06152          }
06153       }
06154    }
06155    if (needdestroy) {
06156       pvt_set_needdestroy(p, "hangup");
06157    }
06158    sip_pvt_unlock(p);
06159    return 0;
06160 }
06161 
06162 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06163 static void try_suggested_sip_codec(struct sip_pvt *p)
06164 {
06165    int fmt;
06166    const char *codec;
06167 
06168    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06169    if (!codec) 
06170       return;
06171 
06172    fmt = ast_getformatbyname(codec);
06173    if (fmt) {
06174       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06175       if (p->jointcapability & fmt) {
06176          p->jointcapability &= fmt;
06177          p->capability &= fmt;
06178       } else
06179          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06180    } else
06181       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06182    return;  
06183 }
06184 
06185 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
06186  * Part of PBX interface */
06187 static int sip_answer(struct ast_channel *ast)
06188 {
06189    int res = 0;
06190    struct sip_pvt *p = ast->tech_pvt;
06191 
06192    sip_pvt_lock(p);
06193    if (ast->_state != AST_STATE_UP) {
06194       try_suggested_sip_codec(p);   
06195 
06196       ast_setstate(ast, AST_STATE_UP);
06197       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06198       ast_rtp_new_source(p->rtp);
06199       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
06200       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06201    }
06202    sip_pvt_unlock(p);
06203    return res;
06204 }
06205 
06206 /*! \brief Send frame to media channel (rtp) */
06207 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06208 {
06209    struct sip_pvt *p = ast->tech_pvt;
06210    int res = 0;
06211 
06212    switch (frame->frametype) {
06213    case AST_FRAME_VOICE:
06214       if (!(frame->subclass & ast->nativeformats)) {
06215          char s1[512], s2[512], s3[512];
06216          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
06217             frame->subclass, 
06218             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06219             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
06220             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
06221             ast->readformat,
06222             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
06223             ast->writeformat);
06224          return 0;
06225       }
06226       if (p) {
06227          sip_pvt_lock(p);
06228          if (p->rtp) {
06229             /* If channel is not up, activate early media session */
06230             if ((ast->_state != AST_STATE_UP) &&
06231                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06232                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06233                ast_rtp_new_source(p->rtp);
06234                if (!global_prematuremediafilter) {
06235                   p->invitestate = INV_EARLY_MEDIA;
06236                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06237                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06238                }
06239             } else if (p->t38.state == T38_ENABLED) {
06240                /* drop frame, can't sent VOICE frames while in T.38 mode */
06241             } else {
06242                p->lastrtptx = time(NULL);
06243                res = ast_rtp_write(p->rtp, frame);
06244             }
06245          }
06246          sip_pvt_unlock(p);
06247       }
06248       break;
06249    case AST_FRAME_VIDEO:
06250       if (p) {
06251          sip_pvt_lock(p);
06252          if (p->vrtp) {
06253             /* Activate video early media */
06254             if ((ast->_state != AST_STATE_UP) &&
06255                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06256                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06257                p->invitestate = INV_EARLY_MEDIA;
06258                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06259                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06260             }
06261             p->lastrtptx = time(NULL);
06262             res = ast_rtp_write(p->vrtp, frame);
06263          }
06264          sip_pvt_unlock(p);
06265       }
06266       break;
06267    case AST_FRAME_TEXT:
06268       if (p) {
06269          sip_pvt_lock(p);
06270          if (p->red) {
06271             red_buffer_t140(p->trtp, frame);
06272          } else {
06273             if (p->trtp) {
06274                /* Activate text early media */
06275                if ((ast->_state != AST_STATE_UP) &&
06276                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06277                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06278                   p->invitestate = INV_EARLY_MEDIA;
06279                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06280                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06281                }
06282                p->lastrtptx = time(NULL);
06283                res = ast_rtp_write(p->trtp, frame);
06284             }
06285          }
06286          sip_pvt_unlock(p);
06287       }
06288       break;
06289    case AST_FRAME_IMAGE:
06290       return 0;
06291       break;
06292    case AST_FRAME_MODEM:
06293       if (p) {
06294          sip_pvt_lock(p);
06295          /* UDPTL requires two-way communication, so early media is not needed here.
06296             we simply forget the frames if we get modem frames before the bridge is up.
06297             Fax will re-transmit.
06298          */
06299          if ((ast->_state == AST_STATE_UP) &&
06300              p->udptl &&
06301              (p->t38.state == T38_ENABLED)) {
06302             res = ast_udptl_write(p->udptl, frame);
06303          }
06304          sip_pvt_unlock(p);
06305       }
06306       break;
06307    default: 
06308       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06309       return 0;
06310    }
06311 
06312    return res;
06313 }
06314 
06315 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06316         Basically update any ->owner links */
06317 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06318 {
06319    int ret = -1;
06320    struct sip_pvt *p;
06321 
06322    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06323       ast_debug(1, "New channel is zombie\n");
06324    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06325       ast_debug(1, "Old channel is zombie\n");
06326 
06327    if (!newchan || !newchan->tech_pvt) {
06328       if (!newchan)
06329          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06330       else
06331          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06332       return -1;
06333    }
06334    p = newchan->tech_pvt;
06335 
06336    sip_pvt_lock(p);
06337    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06338    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06339    if (p->owner != oldchan)
06340       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06341    else {
06342       p->owner = newchan;
06343       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06344          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06345          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06346          redirect of both channels). Note that a channel can not be masqueraded *into*
06347          a native bridge. So there is no danger that this breaks a native bridge that
06348          should stay up. */
06349       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06350       ret = 0;
06351    }
06352    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06353 
06354    sip_pvt_unlock(p);
06355    return ret;
06356 }
06357 
06358 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06359 {
06360    struct sip_pvt *p = ast->tech_pvt;
06361    int res = 0;
06362 
06363    sip_pvt_lock(p);
06364    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06365    case SIP_DTMF_INBAND:
06366       res = -1; /* Tell Asterisk to generate inband indications */
06367       break;
06368    case SIP_DTMF_RFC2833:
06369       if (p->rtp)
06370          ast_rtp_senddigit_begin(p->rtp, digit);
06371       break;
06372    default:
06373       break;
06374    }
06375    sip_pvt_unlock(p);
06376 
06377    return res;
06378 }
06379 
06380 /*! \brief Send DTMF character on SIP channel
06381    within one call, we're able to transmit in many methods simultaneously */
06382 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06383 {
06384    struct sip_pvt *p = ast->tech_pvt;
06385    int res = 0;
06386 
06387    sip_pvt_lock(p);
06388    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06389    case SIP_DTMF_INFO:
06390    case SIP_DTMF_SHORTINFO:
06391       transmit_info_with_digit(p, digit, duration);
06392       break;
06393    case SIP_DTMF_RFC2833:
06394       if (p->rtp)
06395          ast_rtp_senddigit_end(p->rtp, digit);
06396       break;
06397    case SIP_DTMF_INBAND:
06398       res = -1; /* Tell Asterisk to stop inband indications */
06399       break;
06400    }
06401    sip_pvt_unlock(p);
06402 
06403    return res;
06404 }
06405 
06406 /*! \brief Transfer SIP call */
06407 static int sip_transfer(struct ast_channel *ast, const char *dest)
06408 {
06409    struct sip_pvt *p = ast->tech_pvt;
06410    int res;
06411 
06412    if (dest == NULL) /* functions below do not take a NULL */
06413       dest = "";
06414    sip_pvt_lock(p);
06415    if (ast->_state == AST_STATE_RING)
06416       res = sip_sipredirect(p, dest);
06417    else
06418       res = transmit_refer(p, dest);
06419    sip_pvt_unlock(p);
06420    return res;
06421 }
06422 
06423 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06424 static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06425 {
06426    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06427       return;
06428    }
06429    switch (parameters->request_response) {
06430    case AST_T38_NEGOTIATED:
06431    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06432       /* Negotiation can not take place without a valid max_ifp value. */
06433       if (!parameters->max_ifp) {
06434             change_t38_state(p, T38_DISABLED);
06435             if (p->t38.state == T38_PEER_REINVITE) {
06436                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06437                transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06438             }
06439             break;
06440       } else if (p->t38.state == T38_PEER_REINVITE) {
06441          AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06442          p->t38.our_parms = *parameters;
06443          /* modify our parameters to conform to the peer's parameters,
06444           * based on the rules in the ITU T.38 recommendation
06445           */
06446          if (!p->t38.their_parms.fill_bit_removal) {
06447             p->t38.our_parms.fill_bit_removal = FALSE;
06448          }
06449          if (!p->t38.their_parms.transcoding_mmr) {
06450             p->t38.our_parms.transcoding_mmr = FALSE;
06451          }
06452          if (!p->t38.their_parms.transcoding_jbig) {
06453             p->t38.our_parms.transcoding_jbig = FALSE;
06454          }
06455          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06456          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06457          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06458          change_t38_state(p, T38_ENABLED);
06459          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06460       } else if (p->t38.state != T38_ENABLED) {
06461          p->t38.our_parms = *parameters;
06462          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06463          change_t38_state(p, T38_LOCAL_REINVITE);
06464          if (!p->pendinginvite) {
06465             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06466          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06467             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06468          }
06469       }
06470       break;
06471    case AST_T38_TERMINATED:
06472    case AST_T38_REFUSED:
06473    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06474       if (p->t38.state == T38_PEER_REINVITE) {
06475          AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
06476          change_t38_state(p, T38_DISABLED);
06477          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06478       } else if (p->t38.state == T38_ENABLED)
06479          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06480       break;
06481    default:
06482       break;
06483    }
06484 }
06485 
06486 /*! \brief Play indication to user 
06487  * With SIP a lot of indications is sent as messages, letting the device play
06488    the indication - busy signal, congestion etc 
06489    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06490 */
06491 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06492 {
06493    struct sip_pvt *p = ast->tech_pvt;
06494    int res = 0;
06495 
06496    sip_pvt_lock(p);
06497    switch(condition) {
06498    case AST_CONTROL_RINGING:
06499       if (ast->_state == AST_STATE_RING) {
06500          p->invitestate = INV_EARLY_MEDIA;
06501          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06502              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06503             /* Send 180 ringing if out-of-band seems reasonable */
06504             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06505             ast_set_flag(&p->flags[0], SIP_RINGING);
06506             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06507                break;
06508          } else {
06509             /* Well, if it's not reasonable, just send in-band */
06510          }
06511       }
06512       res = -1;
06513       break;
06514    case AST_CONTROL_BUSY:
06515       if (ast->_state != AST_STATE_UP) {
06516          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06517          p->invitestate = INV_COMPLETED;
06518          sip_alreadygone(p);
06519          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06520          break;
06521       }
06522       res = -1;
06523       break;
06524    case AST_CONTROL_CONGESTION:
06525       if (ast->_state != AST_STATE_UP) {
06526          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06527          p->invitestate = INV_COMPLETED;
06528          sip_alreadygone(p);
06529          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06530          break;
06531       }
06532       res = -1;
06533       break;
06534    case AST_CONTROL_PROCEEDING:
06535       if ((ast->_state != AST_STATE_UP) &&
06536           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06537           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06538          transmit_response(p, "100 Trying", &p->initreq);
06539          p->invitestate = INV_PROCEEDING;  
06540          break;
06541       }
06542       res = -1;
06543       break;
06544    case AST_CONTROL_PROGRESS:
06545       if ((ast->_state != AST_STATE_UP) &&
06546           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06547           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06548          p->invitestate = INV_EARLY_MEDIA;
06549          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06550          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06551          break;
06552       }
06553       res = -1;
06554       break;
06555    case AST_CONTROL_HOLD:
06556       ast_rtp_new_source(p->rtp);
06557       ast_moh_start(ast, data, p->mohinterpret);
06558       break;
06559    case AST_CONTROL_UNHOLD:
06560       ast_rtp_new_source(p->rtp);
06561       ast_moh_stop(ast);
06562       break;
06563    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06564       if (p->vrtp && !p->novideo) {
06565          transmit_info_with_vidupdate(p);
06566          /* ast_rtcp_send_h261fur(p->vrtp); */
06567       } else
06568          res = -1;
06569       break;
06570    case AST_CONTROL_T38_PARAMETERS:
06571       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06572          ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
06573       } else {
06574          const struct ast_control_t38_parameters *parameters = data;
06575          interpret_t38_parameters(p, parameters);
06576       }
06577       break;
06578    case AST_CONTROL_SRCUPDATE:
06579       ast_rtp_new_source(p->rtp);
06580       break;
06581    case -1:
06582       res = -1;
06583       break;
06584    default:
06585       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06586       res = -1;
06587       break;
06588    }
06589    sip_pvt_unlock(p);
06590    return res;
06591 }
06592 
06593 
06594 /*! \brief Initiate a call in the SIP channel
06595    called from sip_request_call (calls from the pbx ) for outbound channels
06596    and from handle_request_invite for inbound channels
06597    
06598 */
06599 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06600 {
06601    struct ast_channel *tmp;
06602    struct ast_variable *v = NULL;
06603    int fmt;
06604    int what;
06605    int video;
06606    int text;
06607    int needvideo = 0;
06608    int needtext = 0;
06609    char buf[SIPBUFSIZE];
06610    char *decoded_exten;
06611 
06612    {
06613       const char *my_name; /* pick a good name */
06614    
06615       if (title) {
06616          my_name = title;
06617       } else {
06618          char *port = NULL;
06619          my_name = ast_strdupa(i->fromdomain);
06620          if ((port = strchr(i->fromdomain, ':'))) {
06621             *port = '\0';
06622          }
06623       }
06624 
06625       sip_pvt_unlock(i);
06626       /* Don't hold a sip pvt lock while we allocate a channel */
06627       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
06628 
06629    }
06630    if (!tmp) {
06631       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06632       sip_pvt_lock(i);
06633       return NULL;
06634    }
06635    sip_pvt_lock(i);
06636 
06637    tmp->tech = ( ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ?  &sip_tech_info : &sip_tech;
06638 
06639    /* Select our native format based on codec preference until we receive
06640       something from another device to the contrary. */
06641    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06642       what = i->jointcapability;
06643       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06644       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06645    } else if (i->capability) {      /* Our configured capability for this peer */
06646       what = i->capability;
06647       video = i->capability & AST_FORMAT_VIDEO_MASK;
06648       text = i->capability & AST_FORMAT_TEXT_MASK;
06649    } else {
06650       what = global_capability;  /* Global codec support */
06651       video = global_capability & AST_FORMAT_VIDEO_MASK;
06652       text = global_capability & AST_FORMAT_TEXT_MASK;
06653    }
06654 
06655    /* Set the native formats for audio  and merge in video */
06656    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06657    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06658    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06659    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06660    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06661    if (i->prefcodec)
06662       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06663 
06664    /* XXX Why are we choosing a codec from the native formats?? */
06665    fmt = ast_best_codec(tmp->nativeformats);
06666 
06667    /* If we have a prefcodec setting, we have an inbound channel that set a 
06668       preferred format for this call. Otherwise, we check the jointcapability
06669       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06670     */
06671    if (i->vrtp) {
06672       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06673          needvideo = AST_FORMAT_VIDEO_MASK;
06674       else if (i->prefcodec)
06675          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06676       else
06677          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06678    }
06679 
06680    if (i->trtp) {
06681       if (i->prefcodec)
06682          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06683       else
06684          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06685    }
06686 
06687    if (needvideo) 
06688       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06689    else
06690       ast_debug(3, "This channel will not be able to handle video.\n");
06691 
06692    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06693        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06694       int features = 0;
06695 
06696       if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
06697          features |= DSP_FEATURE_DIGIT_DETECT;
06698       }
06699 
06700       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06701          features |= DSP_FEATURE_FAX_DETECT;
06702       }
06703 
06704       i->dsp = ast_dsp_new();
06705       ast_dsp_set_features(i->dsp, features);
06706       if (global_relaxdtmf)
06707          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06708          }
06709 
06710    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06711    if (i->rtp) {
06712       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06713       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06714    }
06715    if (needvideo && i->vrtp) {
06716       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06717       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06718    }
06719    if (needtext && i->trtp) 
06720       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06721    if (i->udptl)
06722       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06723 
06724    if (state == AST_STATE_RING)
06725       tmp->rings = 1;
06726    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06727    tmp->writeformat = fmt;
06728    tmp->rawwriteformat = fmt;
06729    tmp->readformat = fmt;
06730    tmp->rawreadformat = fmt;
06731    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06732 
06733    tmp->callgroup = i->callgroup;
06734    tmp->pickupgroup = i->pickupgroup;
06735    tmp->cid.cid_pres = i->callingpres;
06736    if (!ast_strlen_zero(i->parkinglot))
06737       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06738    if (!ast_strlen_zero(i->accountcode))
06739       ast_string_field_set(tmp, accountcode, i->accountcode);
06740    if (i->amaflags)
06741       tmp->amaflags = i->amaflags;
06742    if (!ast_strlen_zero(i->language))
06743       ast_string_field_set(tmp, language, i->language);
06744    i->owner = tmp;
06745    ast_module_ref(ast_module_info->self);
06746    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06747    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06748     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06749     * structure so that there aren't issues when forming URI's
06750     */
06751    decoded_exten = ast_strdupa(i->exten);
06752    ast_uri_decode(decoded_exten);
06753    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06754 
06755    /* Don't use ast_set_callerid() here because it will
06756     * generate an unnecessary NewCallerID event  */
06757    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06758    if (!ast_strlen_zero(i->rdnis))
06759       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06760    
06761    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06762       tmp->cid.cid_dnid = ast_strdup(i->exten);
06763 
06764    tmp->priority = 1;
06765    if (!ast_strlen_zero(i->uri))
06766       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06767    if (!ast_strlen_zero(i->domain))
06768       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06769    if (!ast_strlen_zero(i->callid))
06770       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06771    if (i->rtp)
06772       ast_jb_configure(tmp, &global_jbconf);
06773 
06774    /* Set channel variables for this call from configuration */
06775    for (v = i->chanvars ; v ; v = v->next) {
06776       char valuebuf[1024];
06777       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
06778    }
06779 
06780    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06781       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06782       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06783       ast_hangup(tmp);
06784       tmp = NULL;
06785    }
06786 
06787    if (i->do_history)
06788       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06789 
06790    /* Inform manager user about new channel and their SIP call ID */
06791    if (sip_cfg.callevents)
06792       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06793          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06794          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06795 
06796    return tmp;
06797 }
06798 
06799 /*! \brief Reads one line of SIP message body */
06800 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
06801 {
06802    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
06803       return ast_skip_blanks(line + nameLen + 1);
06804 
06805    return "";
06806 }
06807 
06808 /*! \brief Lookup 'name' in the SDP starting
06809  * at the 'start' line. Returns the matching line, and 'start'
06810  * is updated with the next line number.
06811  */
06812 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06813 {
06814    int len = strlen(name);
06815 
06816    while (*start < (req->sdp_start + req->sdp_count)) {
06817       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
06818       if (r[0] != '\0')
06819          return r;
06820    }
06821 
06822    /* if the line was not found, ensure that *start points past the SDP */
06823    (*start)++;
06824 
06825    return "";
06826 }
06827 
06828 /*! \brief Fetches the next valid SDP line between the 'start' line
06829  * (inclusive) and the 'stop' line (exclusive). Returns the type
06830  * ('a', 'c', ...) and matching line in reference 'start' is updated
06831  * with the next line number.
06832  */
06833 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06834 {
06835    char type = '\0';
06836    const char *line = NULL;
06837 
06838    if (stop > (req->sdp_start + req->sdp_count)) {
06839       stop = req->sdp_start + req->sdp_count;
06840    }
06841 
06842    while (*start < stop) {
06843       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06844       if (line[1] == '=') {
06845          type = line[0];
06846          *value = ast_skip_blanks(line + 2);
06847          break;
06848       }
06849    }
06850 
06851    return type;
06852 }
06853 
06854 /*! \brief Get a specific line from the message body */
06855 static char *get_body(struct sip_request *req, char *name, char delimiter) 
06856 {
06857    int x;
06858    int len = strlen(name);
06859    char *r;
06860 
06861    for (x = 0; x < req->lines; x++) {
06862       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
06863       if (r[0] != '\0')
06864          return r;
06865    }
06866 
06867    return "";
06868 }
06869 
06870 /*! \brief Find compressed SIP alias */
06871 static const char *find_alias(const char *name, const char *_default)
06872 {
06873    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06874    static const struct cfalias {
06875       char * const fullname;
06876       char * const shortname;
06877    } aliases[] = {
06878       { "Content-Type",  "c" },
06879       { "Content-Encoding",    "e" },
06880       { "From",       "f" },
06881       { "Call-ID",       "i" },
06882       { "Contact",       "m" },
06883       { "Content-Length",   "l" },
06884       { "Subject",       "s" },
06885       { "To",         "t" },
06886       { "Supported",     "k" },
06887       { "Refer-To",      "r" },
06888       { "Referred-By",   "b" },
06889       { "Allow-Events",  "u" },
06890       { "Event",      "o" },
06891       { "Via",     "v" },
06892       { "Accept-Contact",      "a" },
06893       { "Reject-Contact",      "j" },
06894       { "Request-Disposition", "d" },
06895       { "Session-Expires",     "x" },
06896       { "Identity",            "y" },
06897       { "Identity-Info",       "n" },
06898    };
06899    int x;
06900 
06901    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06902       if (!strcasecmp(aliases[x].fullname, name))
06903          return aliases[x].shortname;
06904    }
06905 
06906    return _default;
06907 }
06908 
06909 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06910 {
06911    int pass;
06912 
06913    /*
06914     * Technically you can place arbitrary whitespace both before and after the ':' in
06915     * a header, although RFC3261 clearly says you shouldn't before, and place just
06916     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
06917     * a good idea to say you can do it, and if you can do it, why in the hell would.
06918     * you say you shouldn't.
06919     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06920     * and we always allow spaces after that for compatibility.
06921     */
06922    for (pass = 0; name && pass < 2;pass++) {
06923       int x, len = strlen(name);
06924       for (x = *start; x < req->headers; x++) {
06925          char *header = REQ_OFFSET_TO_STR(req, header[x]);
06926          if (!strncasecmp(header, name, len)) {
06927             char *r = header + len; /* skip name */
06928             if (sip_cfg.pedanticsipchecking)
06929                r = ast_skip_blanks(r);
06930 
06931             if (*r == ':') {
06932                *start = x+1;
06933                return ast_skip_blanks(r+1);
06934             }
06935          }
06936       }
06937       if (pass == 0) /* Try aliases */
06938          name = find_alias(name, NULL);
06939    }
06940 
06941    /* Don't return NULL, so get_header is always a valid pointer */
06942    return "";
06943 }
06944 
06945 /*! \brief Get header from SIP request 
06946    \return Always return something, so don't check for NULL because it won't happen :-)
06947 */
06948 static const char *get_header(const struct sip_request *req, const char *name)
06949 {
06950    int start = 0;
06951    return __get_header(req, name, &start);
06952 }
06953 
06954 /*! \brief Read RTP from network */
06955 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06956 {
06957    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06958    struct ast_frame *f;
06959    
06960    if (!p->rtp) {
06961       /* We have no RTP allocated for this channel */
06962       return &ast_null_frame;
06963    }
06964 
06965    switch(ast->fdno) {
06966    case 0:
06967       f = ast_rtp_read(p->rtp);  /* RTP Audio */
06968       break;
06969    case 1:
06970       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
06971       break;
06972    case 2:
06973       f = ast_rtp_read(p->vrtp); /* RTP Video */
06974       break;
06975    case 3:
06976       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
06977       break;
06978    case 4:
06979       f = ast_rtp_read(p->trtp); /* RTP Text */
06980       if (sipdebug_text) {
06981          int i;
06982          unsigned char* arr = f->data.ptr;
06983          for (i=0; i < f->datalen; i++)
06984             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06985          ast_verbose(" -> ");
06986          for (i=0; i < f->datalen; i++)
06987             ast_verbose("%02X ", arr[i]);
06988          ast_verbose("\n");
06989       }
06990       break;
06991    case 5:
06992       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
06993       break;
06994    default:
06995       f = &ast_null_frame;
06996    }
06997    /* Don't forward RFC2833 if we're not supposed to */
06998    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06999        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07000       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
07001       return &ast_null_frame;
07002    }
07003 
07004    /* We already hold the channel lock */
07005    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07006       return f;
07007 
07008    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07009       if (!(f->subclass & p->jointcapability)) {
07010          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07011             ast_getformatname(f->subclass), p->owner->name);
07012          return &ast_null_frame;
07013       }
07014       ast_debug(1, "Oooh, format changed to %d %s\n",
07015          f->subclass, ast_getformatname(f->subclass));
07016       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
07017       ast_set_read_format(p->owner, p->owner->readformat);
07018       ast_set_write_format(p->owner, p->owner->writeformat);
07019    }
07020 
07021    if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
07022       f = ast_dsp_process(p->owner, p->dsp, f);
07023                 if (f && f->frametype == AST_FRAME_DTMF) {
07024          if (f->subclass == 'f') {
07025                                 if (option_debug)
07026                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
07027                                 *faxdetect = 1;
07028             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07029             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07030                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07031             } else {
07032                ast_dsp_free(p->dsp);
07033                p->dsp = NULL;
07034             }
07035          } else {
07036             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
07037          }
07038       }
07039    }
07040    
07041    return f;
07042 }
07043 
07044 /*! \brief Read SIP RTP from channel */
07045 static struct ast_frame *sip_read(struct ast_channel *ast)
07046 {
07047    struct ast_frame *fr;
07048    struct sip_pvt *p = ast->tech_pvt;
07049    int faxdetected = FALSE;
07050 
07051    sip_pvt_lock(p);
07052    fr = sip_rtp_read(ast, p, &faxdetected);
07053    p->lastrtprx = time(NULL);
07054 
07055    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07056    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
07057       ast_channel_lock(ast);
07058       if (strcmp(ast->exten, "fax")) {
07059          const char *target_context = S_OR(ast->macrocontext, ast->context);
07060          ast_channel_unlock(ast);
07061          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
07062             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension\n", ast->name);
07063             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07064             if (ast_async_goto(ast, target_context, "fax", 1)) {
07065                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07066             }
07067             fr = &ast_null_frame;
07068          } else {
07069             ast_log(LOG_NOTICE, "Fax detected but no fax extension\n");
07070                         }
07071       } else {
07072          ast_channel_unlock(ast);
07073                 }
07074         }
07075 
07076    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07077    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07078       fr = &ast_null_frame;
07079    }
07080 
07081    sip_pvt_unlock(p);
07082 
07083    return fr;
07084 }
07085 
07086 
07087 /*! \brief Generate 32 byte random string for callid's etc */
07088 static char *generate_random_string(char *buf, size_t size)
07089 {
07090    long val[4];
07091    int x;
07092 
07093    for (x=0; x<4; x++)
07094       val[x] = ast_random();
07095    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07096 
07097    return buf;
07098 }
07099 
07100 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
07101 static void build_callid_pvt(struct sip_pvt *pvt)
07102 {
07103    char buf[33];
07104 
07105    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
07106    
07107    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07108 
07109 }
07110 
07111 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07112 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
07113 {
07114    char buf[33];
07115 
07116    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
07117 
07118    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07119 }
07120 
07121 /*! \brief Make our SIP dialog tag */
07122 static void make_our_tag(char *tagbuf, size_t len)
07123 {
07124    snprintf(tagbuf, len, "as%08lx", ast_random());
07125 }
07126 
07127 /*! \brief Allocate Session-Timers struct w/in dialog */
07128 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07129 {
07130    struct sip_st_dlg *stp;
07131 
07132    if (p->stimer) {
07133       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07134       return p->stimer;
07135    }
07136 
07137    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07138       return NULL;
07139 
07140    p->stimer = stp;
07141 
07142    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07143 
07144    return p->stimer;
07145 }
07146 
07147 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07148  * Returns a reference to the object so whoever uses it later must
07149  * remember to release the reference.
07150  */
07151 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
07152              int useglobal_nat, const int intended_method, struct sip_request *req)
07153 {
07154    struct sip_pvt *p;
07155 
07156    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07157       return NULL;
07158 
07159    if (ast_string_field_init(p, 512)) {
07160       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07161       return NULL;
07162    }
07163 
07164    if (req) {
07165       set_socket_transport(&p->socket, req->socket.type); /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07166    } else {
07167       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07168    }
07169 
07170    p->socket.fd = -1;
07171    p->method = intended_method;
07172    p->initid = -1;
07173    p->waitid = -1;
07174    p->autokillid = -1;
07175    p->request_queue_sched_id = -1;
07176    p->provisional_keepalive_sched_id = -1;
07177    p->t38id = -1;
07178    p->subscribed = NONE;
07179    p->stateid = -1;
07180    p->sessionversion_remote = -1;
07181    p->session_modify = TRUE;
07182    p->stimer = NULL;
07183    p->prefs = default_prefs;     /* Set default codecs for this call */
07184 
07185    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07186       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07187       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07188    }
07189 
07190    if (!sin)
07191       p->ourip = internip;
07192    else {
07193       p->sa = *sin;
07194       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
07195    }
07196 
07197    /* Copy global flags to this PVT at setup. */
07198    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07199    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07200 
07201    p->do_history = recordhistory;
07202 
07203    p->branch = ast_random();  
07204    make_our_tag(p->tag, sizeof(p->tag));
07205    p->ocseq = INITIAL_CSEQ;
07206 
07207    if (sip_methods[intended_method].need_rtp) {
07208       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07209       /* If the global videosupport flag is on, we always create a RTP interface for video */
07210       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07211          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07212       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
07213          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
07214       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
07215          p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
07216       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
07217             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
07218          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
07219             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
07220             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
07221          if (p->chanvars) {
07222             ast_variables_destroy(p->chanvars);
07223             p->chanvars = NULL;
07224          }
07225          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
07226          return NULL;
07227          p->t38_maxdatagram = global_t38_maxdatagram;
07228       }
07229       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
07230       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
07231       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07232       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
07233       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
07234       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
07235       if (p->vrtp) {
07236          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
07237          ast_rtp_setdtmf(p->vrtp, 0);
07238          ast_rtp_setdtmfcompensate(p->vrtp, 0);
07239          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
07240          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
07241          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
07242       }
07243       if (p->trtp) {
07244          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
07245          ast_rtp_setdtmf(p->trtp, 0);
07246          ast_rtp_setdtmfcompensate(p->trtp, 0);
07247       }
07248       if (p->udptl)
07249          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07250       p->maxcallbitrate = default_maxcallbitrate;
07251       p->autoframing = global_autoframing;
07252       ast_rtp_codec_setpref(p->rtp, &p->prefs);
07253    }
07254 
07255    if (useglobal_nat && sin) {
07256       /* Setup NAT structure according to global settings if we have an address */
07257       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
07258       p->recv = *sin;
07259       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
07260    }
07261 
07262    if (p->method != SIP_REGISTER)
07263       ast_string_field_set(p, fromdomain, default_fromdomain);
07264    build_via(p);
07265    if (!callid)
07266       build_callid_pvt(p);
07267    else
07268       ast_string_field_set(p, callid, callid);
07269    /* Assign default music on hold class */
07270    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07271    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07272    p->capability = global_capability;
07273    p->allowtransfer = sip_cfg.allowtransfer;
07274    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07275        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
07276       p->noncodeccapability |= AST_RTP_DTMF;
07277    if (p->udptl) {
07278       p->t38_maxdatagram = global_t38_maxdatagram;
07279       set_t38_capabilities(p);
07280    }
07281    ast_string_field_set(p, context, sip_cfg.default_context);
07282    ast_string_field_set(p, parkinglot, default_parkinglot);
07283 
07284    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07285 
07286    /* Add to active dialog list */
07287 
07288    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07289    
07290    ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
07291    return p;
07292 }
07293 
07294 /*! \brief argument to the helper function to identify a call */
07295 struct find_call_cb_arg {
07296    enum sipmethod method;
07297    const char *callid;
07298    const char *fromtag;
07299    const char *totag;
07300    const char *tag;
07301 };
07302 
07303 /*!
07304  * code to determine whether this is the pvt that we are looking for.
07305  * Return FALSE if not found, true otherwise. p is unlocked.
07306  */
07307 static int find_call_cb(void *__pvt, void *__arg, int flags)
07308 {
07309    struct sip_pvt *p = __pvt;
07310    struct find_call_cb_arg *arg = __arg;
07311    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
07312    int found = FALSE;
07313    
07314    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
07315       if (arg->method == SIP_REGISTER)
07316          found = (!strcmp(p->callid, arg->callid));
07317       else {
07318          found = !strcmp(p->callid, arg->callid);
07319          if (sip_cfg.pedanticsipchecking && found) {
07320             found = ast_strlen_zero(arg->tag) || ast_strlen_zero(p->theirtag) || !ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED) || !strcmp(p->theirtag, arg->tag);
07321          } 
07322       }
07323       
07324       ast_debug(5, "= %s Their Call ID: %s Their Tag %s Our tag: %s\n", found ? "Found" : "No match", p->callid, p->theirtag, p->tag);
07325       
07326       /* If we get a new request within an existing to-tag - check the to tag as well */
07327       if (sip_cfg.pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
07328          if (p->tag[0] == '\0' && arg->totag[0]) {
07329             /* We have no to tag, but they have. Wrong dialog */
07330             found = FALSE;
07331          } else if (arg->totag[0]) { /* Both have tags, compare them */
07332             if (strcmp(arg->totag, p->tag)) {
07333                found = FALSE; /* This is not our packet */
07334             }
07335          }
07336          if (!found)
07337             ast_debug(5, "= Being pedantic: This is not our match on request: Call ID: %s Ourtag <null> Totag %s Method %s\n", p->callid, arg->totag, sip_methods[arg->method].text);
07338       }
07339    }
07340    return found;
07341 }
07342 
07343 /*! \brief find or create a dialog structure for an incoming SIP message.
07344  * Connect incoming SIP message to current dialog or create new dialog structure
07345  * Returns a reference to the sip_pvt object, remember to give it back once done.
07346  *     Called by handle_incoming(), sipsock_read
07347  */
07348 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
07349 {
07350    struct sip_pvt *p = NULL;
07351    char *tag = "";   /* note, tag is never NULL */
07352    char totag[128];
07353    char fromtag[128];
07354    struct find_call_cb_arg arg;
07355    const char *callid = get_header(req, "Call-ID");
07356    const char *from = get_header(req, "From");
07357    const char *to = get_header(req, "To");
07358    const char *cseq = get_header(req, "Cseq");
07359    struct sip_pvt *sip_pvt_ptr;
07360 
07361    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
07362    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
07363    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
07364          ast_strlen_zero(from) || ast_strlen_zero(cseq))
07365       return NULL;   /* Invalid packet */
07366 
07367    arg.method = req->method;
07368    arg.callid = callid;
07369    arg.fromtag = fromtag;
07370    arg.totag = totag;
07371    arg.tag = ""; /* make sure tag is never NULL */
07372 
07373    if (sip_cfg.pedanticsipchecking) {
07374       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
07375          we need more to identify a branch - so we have to check branch, from
07376          and to tags to identify a call leg.
07377          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
07378          in sip.conf
07379          */
07380       if (gettag(req, "To", totag, sizeof(totag)))
07381          req->has_to_tag = 1; /* Used in handle_request/response */
07382       gettag(req, "From", fromtag, sizeof(fromtag));
07383 
07384       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
07385 
07386       ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
07387 
07388       /* All messages must always have From: tag */
07389       if (ast_strlen_zero(fromtag)) {
07390          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07391          return NULL;
07392       }
07393       /* reject requests that must always have a To: tag */
07394       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
07395          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
07396          return NULL;
07397       }
07398    }
07399 
07400 restartsearch:
07401    if (!sip_cfg.pedanticsipchecking) {
07402       struct sip_pvt tmp_dialog = {
07403          .callid = callid,
07404       };       
07405       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
07406       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
07407          /* Found the call */
07408          sip_pvt_lock(sip_pvt_ptr);
07409          return sip_pvt_ptr;
07410       }
07411    } else { /* in pedantic mode! -- do the fancy linear search */
07412       ao2_lock(dialogs);
07413       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07414       if (p) {
07415          if (sip_pvt_trylock(p)) {
07416             ao2_unlock(dialogs);
07417             usleep(1);
07418             goto restartsearch;
07419          }
07420          ao2_unlock(dialogs);
07421          return p;
07422       }
07423       ao2_unlock(dialogs);
07424    }
07425  
07426    /* See if the method is capable of creating a dialog */
07427    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07428       if (intended_method == SIP_REFER) {
07429          /* We do support REFER, but not outside of a dialog yet */
07430          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07431       } else if (intended_method == SIP_NOTIFY) {
07432          /* We do not support out-of-dialog NOTIFY either,
07433             like voicemail notification, so cancel that early */
07434          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07435       } else {
07436          /* Ok, time to create a new SIP dialog object, a pvt */
07437          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07438             /* Ok, we've created a dialog, let's go and process it */
07439             sip_pvt_lock(p);
07440          } else {
07441             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07442                getting a dialog from sip_alloc. 
07443    
07444                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07445                send an error message.
07446    
07447                Sorry, we apologize for the inconvienience
07448             */
07449             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07450             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07451          }
07452       }
07453       return p; /* can be NULL */
07454    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07455       /* A method we do not support, let's take it on the volley */
07456       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07457       ast_debug(2, "Got a request with unsupported SIP method.\n");
07458    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07459       /* This is a request outside of a dialog that we don't know about */
07460       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07461       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07462    }
07463    /* We do not respond to responses for dialogs that we don't know about, we just drop
07464       the session quickly */
07465    if (intended_method == SIP_RESPONSE)
07466       ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
07467 
07468    return NULL;
07469 }
07470 
07471 /*! \brief Parse register=> line in sip.conf and add to registry */
07472 static int sip_register(const char *value, int lineno)
07473 {
07474    struct sip_registry *reg;
07475    int portnum = 0;
07476    enum sip_transport transport = SIP_TRANSPORT_UDP;
07477    char buf[256] = "";
07478    char *userpart = NULL, *hostpart = NULL;
07479    /* register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] */
07480    AST_DECLARE_APP_ARGS(pre1,
07481       AST_APP_ARG(peer);
07482       AST_APP_ARG(userpart);
07483    );
07484    AST_DECLARE_APP_ARGS(pre2,
07485       AST_APP_ARG(transport);
07486       AST_APP_ARG(blank);
07487       AST_APP_ARG(userpart);
07488    );
07489    AST_DECLARE_APP_ARGS(user1,
07490       AST_APP_ARG(userpart);
07491       AST_APP_ARG(secret);
07492       AST_APP_ARG(authuser);
07493    );
07494    AST_DECLARE_APP_ARGS(host1,
07495       AST_APP_ARG(hostpart);
07496       AST_APP_ARG(expiry);
07497    );
07498    AST_DECLARE_APP_ARGS(host2,
07499       AST_APP_ARG(hostpart);
07500       AST_APP_ARG(extension);
07501    );
07502    AST_DECLARE_APP_ARGS(host3,
07503       AST_APP_ARG(host);
07504       AST_APP_ARG(port);
07505    );
07506 
07507    if (!value)
07508       return -1;
07509    ast_copy_string(buf, value, sizeof(buf));
07510 
07511    /*! register => [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry]
07512     * becomes
07513     *   userpart => [peer?][transport://]user[@domain][:secret[:authuser]]
07514     *   hostpart => host[:port][/extension][~expiry]
07515     */
07516    if ((hostpart = strrchr(buf, '@'))) {
07517       *hostpart++ = '\0';
07518       userpart = buf;
07519    }
07520 
07521    if (ast_strlen_zero(userpart) || ast_strlen_zero(hostpart)) {
07522       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07523       return -1;
07524    }
07525 
07526    /*!
07527     * pre1.peer => peer
07528     * pre1.userpart => [transport://]user[@domain][:secret[:authuser]]
07529     * hostpart => host[:port][/extension][~expiry]
07530     */
07531    AST_NONSTANDARD_RAW_ARGS(pre1, userpart, '?');
07532    if (ast_strlen_zero(pre1.userpart)) {
07533       pre1.userpart = pre1.peer;
07534       pre1.peer = NULL;
07535    }
07536 
07537    /*!
07538     * pre1.peer => peer
07539     * pre2.transport = transport
07540     * pre2.userpart => user[@domain][:secret[:authuser]]
07541     * hostpart => host[:port][/extension][~expiry]
07542     */
07543    AST_NONSTANDARD_RAW_ARGS(pre2, pre1.userpart, '/');
07544    if (ast_strlen_zero(pre2.userpart)) {
07545       pre2.userpart = pre2.transport;
07546       pre2.transport = NULL;
07547    } else {
07548       pre2.transport[strlen(pre2.transport) - 1] = '\0'; /* Remove trailing : */
07549    }
07550 
07551    if (!ast_strlen_zero(pre2.blank)) {
07552       ast_log(LOG_WARNING, "Format for registration is [peer?][transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07553       return -1;
07554    }
07555 
07556    /*!
07557     * pre1.peer => peer
07558     * pre2.transport = transport
07559     * user1.userpart => user[@domain]
07560     * user1.secret => secret
07561     * user1.authuser => authuser
07562     * hostpart => host[:port][/extension][~expiry]
07563     */
07564    AST_NONSTANDARD_RAW_ARGS(user1, pre2.userpart, ':');
07565 
07566    /*!
07567     * pre1.peer => peer
07568     * pre2.transport = transport
07569     * user1.userpart => user[@domain]
07570     * user1.secret => secret
07571     * user1.authuser => authuser
07572     * host1.hostpart => host[:port][/extension]
07573     * host1.expiry => [expiry]
07574     */
07575    AST_NONSTANDARD_RAW_ARGS(host1, hostpart, '~');
07576 
07577    /*!
07578     * pre1.peer => peer
07579     * pre2.transport = transport
07580     * user1.userpart => user[@domain]
07581     * user1.secret => secret
07582     * user1.authuser => authuser
07583     * host2.hostpart => host[:port]
07584     * host2.extension => [extension]
07585     * host1.expiry => [expiry]
07586     */
07587    AST_NONSTANDARD_RAW_ARGS(host2, host1.hostpart, '/');
07588 
07589    /*!
07590     * pre1.peer => peer
07591     * pre2.transport = transport
07592     * user1.userpart => user[@domain]
07593     * user1.secret => secret
07594     * user1.authuser => authuser
07595     * host3.host => host
07596     * host3.port => port
07597     * host2.extension => extension
07598     * host1.expiry => expiry
07599     */
07600    AST_NONSTANDARD_RAW_ARGS(host3, host2.hostpart, ':');
07601 
07602    if (host3.port) {
07603       if (!(portnum = port_str2int(host3.port, 0))) {
07604          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", host3.port, lineno);
07605       }
07606    }
07607 
07608    /* set transport type */
07609    if (!pre2.transport) {
07610       transport = SIP_TRANSPORT_UDP;
07611    } else if (!strncasecmp(pre2.transport, "tcp", 3)) {
07612       transport = SIP_TRANSPORT_TCP;
07613    } else if (!strncasecmp(pre2.transport, "tls", 3)) {
07614       transport = SIP_TRANSPORT_TLS;
07615    } else if (!strncasecmp(pre2.transport, "udp", 3)) {
07616       transport = SIP_TRANSPORT_UDP;
07617    } else {
07618       transport = SIP_TRANSPORT_UDP;
07619       ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", pre2.transport, lineno);
07620    }
07621 
07622    /* if no portnum specified, set default for transport */
07623    if (!portnum) {
07624       if (transport == SIP_TRANSPORT_TLS) {
07625          portnum = STANDARD_TLS_PORT;
07626       } else {
07627          portnum = STANDARD_SIP_PORT;
07628       }
07629    }
07630 
07631    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07632       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07633       return -1;
07634    }
07635 
07636    if (ast_string_field_init(reg, 256)) {
07637       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07638       ast_free(reg);
07639       return -1;
07640    }
07641 
07642    ast_atomic_fetchadd_int(&regobjs, 1);
07643    ASTOBJ_INIT(reg);
07644    ast_string_field_set(reg, callback, ast_strip_quoted(S_OR(host2.extension, "s"), "\"", "\""));
07645    ast_string_field_set(reg, username, ast_strip_quoted(S_OR(user1.userpart, ""), "\"", "\""));
07646    ast_string_field_set(reg, hostname, ast_strip_quoted(S_OR(host3.host, ""), "\"", "\""));
07647    ast_string_field_set(reg, authuser, ast_strip_quoted(S_OR(user1.authuser, ""), "\"", "\""));
07648    ast_string_field_set(reg, secret, ast_strip_quoted(S_OR(user1.secret, ""), "\"", "\""));
07649    ast_string_field_set(reg, peername, ast_strip_quoted(S_OR(pre1.peer, ""), "\"", "\""));
07650 
07651    reg->transport = transport;
07652    reg->timeout = reg->expire = -1;
07653    reg->refresh = reg->expiry = reg->configured_expiry = (host1.expiry ? atoi(ast_strip_quoted(host1.expiry, "\"", "\"")) : default_expiry);
07654    reg->portno = portnum;
07655    reg->callid_valid = FALSE;
07656    reg->ocseq = INITIAL_CSEQ;
07657    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07658    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07659    return 0;
07660 }
07661 
07662 /*! \brief Parse mwi=> line in sip.conf and add to list */
07663 static int sip_subscribe_mwi(const char *value, int lineno)
07664 {
07665    struct sip_subscription_mwi *mwi;
07666    int portnum = 0;
07667    enum sip_transport transport = SIP_TRANSPORT_UDP;
07668    char buf[256] = "";
07669    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
07670    
07671    if (!value) {
07672       return -1;
07673    }
07674    
07675    ast_copy_string(buf, value, sizeof(buf));
07676 
07677    sip_parse_host(buf, lineno, &username, &portnum, &transport);
07678    
07679    if ((hostname = strrchr(username, '@'))) {
07680       *hostname++ = '\0';
07681    }
07682    
07683    if ((secret = strchr(username, ':'))) {
07684       *secret++ = '\0';
07685       if ((authuser = strchr(secret, ':'))) {
07686          *authuser++ = '\0';
07687       }
07688    }
07689    
07690    if ((mailbox = strchr(hostname, '/'))) {
07691       *mailbox++ = '\0';
07692    }
07693 
07694    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
07695       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port][/mailbox] at line %d\n", lineno);
07696       return -1;
07697    }
07698    
07699    if ((porta = strchr(hostname, ':'))) {
07700       *porta++ = '\0';
07701       if (!(portnum = atoi(porta))) {
07702          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
07703          return -1;
07704       }
07705    }
07706    
07707    if (!(mwi = ast_calloc(1, sizeof(*mwi)))) {
07708       return -1;
07709    }
07710    
07711    if (ast_string_field_init(mwi, 256)) {
07712       ast_free(mwi);
07713       return -1;
07714    }
07715    
07716    ASTOBJ_INIT(mwi);
07717    ast_string_field_set(mwi, username, username);
07718    if (secret) {
07719       ast_string_field_set(mwi, secret, secret);
07720    }
07721    if (authuser) {
07722       ast_string_field_set(mwi, authuser, authuser);
07723    }
07724    ast_string_field_set(mwi, hostname, hostname);
07725    ast_string_field_set(mwi, mailbox, mailbox);
07726    mwi->resub = -1;
07727    mwi->portno = portnum;
07728    mwi->transport = transport;
07729    
07730    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
07731    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
07732    
07733    return 0;
07734 }
07735 
07736 /*! \brief  Parse multiline SIP headers into one header
07737    This is enabled if pedanticsipchecking is enabled */
07738 static int lws2sws(char *msgbuf, int len) 
07739 {
07740    int h = 0, t = 0; 
07741    int lws = 0; 
07742 
07743    for (; h < len;) { 
07744       /* Eliminate all CRs */ 
07745       if (msgbuf[h] == '\r') { 
07746          h++; 
07747          continue; 
07748       } 
07749       /* Check for end-of-line */ 
07750       if (msgbuf[h] == '\n') { 
07751          /* Check for end-of-message */ 
07752          if (h + 1 == len) 
07753             break; 
07754          /* Check for a continuation line */ 
07755          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07756             /* Merge continuation line */ 
07757             h++; 
07758             continue; 
07759          } 
07760          /* Propagate LF and start new line */ 
07761          msgbuf[t++] = msgbuf[h++]; 
07762          lws = 0;
07763          continue; 
07764       } 
07765       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07766          if (lws) { 
07767             h++; 
07768             continue; 
07769          } 
07770          msgbuf[t++] = msgbuf[h++]; 
07771          lws = 1; 
07772          continue; 
07773       } 
07774       msgbuf[t++] = msgbuf[h++]; 
07775       if (lws) 
07776          lws = 0; 
07777    } 
07778    msgbuf[t] = '\0'; 
07779    return t; 
07780 }
07781 
07782 /*! \brief Parse a SIP message 
07783    \note this function is used both on incoming and outgoing packets
07784 */
07785 static int parse_request(struct sip_request *req)
07786 {
07787    char *c = req->data->str;
07788    ptrdiff_t *dst = req->header;
07789    int i = 0, lim = SIP_MAX_HEADERS - 1;
07790    unsigned int skipping_headers = 0;
07791    ptrdiff_t current_header_offset = 0;
07792    char *previous_header = "";
07793 
07794    req->header[0] = 0;
07795    req->headers = -1;   /* mark that we are working on the header */
07796    for (; *c; c++) {
07797       if (*c == '\r') {    /* remove \r */
07798          *c = '\0';
07799       } else if (*c == '\n') {   /* end of this line */
07800          *c = '\0';
07801          current_header_offset = (c + 1) - req->data->str;
07802          previous_header = req->data->str + dst[i];
07803          if (skipping_headers) {
07804             /* check to see if this line is blank; if so, turn off
07805                the skipping flag, so the next line will be processed
07806                as a body line */
07807             if (ast_strlen_zero(previous_header)) {
07808                skipping_headers = 0;
07809             }
07810             dst[i] = current_header_offset; /* record start of next line */
07811             continue;
07812          }
07813          if (sipdebug) {
07814             ast_debug(4, "%7s %2d [%3d]: %s\n",
07815                  req->headers < 0 ? "Header" : "Body",
07816                  i, (int) strlen(previous_header), previous_header);
07817          }
07818          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07819             req->headers = i; /* record number of header lines */
07820             dst = req->line;  /* start working on the body */
07821             i = 0;
07822             lim = SIP_MAX_LINES - 1;
07823          } else { /* move to next line, check for overflows */
07824             if (i++ == lim) {
07825                /* if we're processing headers, then skip any remaining
07826                   headers and move on to processing the body, otherwise
07827                   we're done */
07828                if (req->headers != -1) {
07829                   break;
07830                } else {
07831                   req->headers = i;
07832                   dst = req->line;
07833                   i = 0;
07834                   lim = SIP_MAX_LINES - 1;
07835                   skipping_headers = 1;
07836                }
07837             }
07838          }
07839          dst[i] = current_header_offset; /* record start of next line */
07840       }
07841    }
07842 
07843    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07844       but since some devices send without, we'll be generous in what we accept. However,
07845       if we've already reached the maximum number of lines for portion of the message
07846       we were parsing, we can't accept any more, so just ignore it.
07847    */
07848    previous_header = req->data->str + dst[i];
07849    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07850       if (sipdebug) {
07851          ast_debug(4, "%7s %2d [%3d]: %s\n",
07852               req->headers < 0 ? "Header" : "Body",
07853               i, (int) strlen(previous_header), previous_header );
07854       }
07855       i++;
07856    }
07857 
07858    /* update count of header or body lines */
07859    if (req->headers >= 0) {   /* we are in the body */
07860       req->lines = i;
07861    } else {       /* no body */
07862       req->headers = i;
07863       req->lines = 0;
07864       /* req->data->used will be a NULL byte */
07865       req->line[0] = ast_str_strlen(req->data);
07866    }
07867 
07868    if (*c) {
07869       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07870    }
07871 
07872    /* Split up the first line parts */
07873    return determine_firstline_parts(req);
07874 }
07875 
07876 /*!
07877   \brief Determine whether a SIP message contains an SDP in its body
07878   \param req the SIP request to process
07879   \return 1 if SDP found, 0 if not found
07880 
07881   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07882   lives in the message body.
07883 */
07884 static int find_sdp(struct sip_request *req)
07885 {
07886    const char *content_type;
07887    const char *content_length;
07888    const char *search;
07889    char *boundary;
07890    unsigned int x;
07891    int boundaryisquoted = FALSE;
07892    int found_application_sdp = FALSE;
07893    int found_end_of_headers = FALSE;
07894 
07895    content_length = get_header(req, "Content-Length");
07896 
07897    if (!ast_strlen_zero(content_length)) {
07898       if (sscanf(content_length, "%30u", &x) != 1) {
07899          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07900          return 0;
07901       }
07902 
07903       /* Content-Length of zero means there can't possibly be an
07904          SDP here, even if the Content-Type says there is */
07905       if (x == 0)
07906          return 0;
07907    }
07908 
07909    content_type = get_header(req, "Content-Type");
07910 
07911    /* if the body contains only SDP, this is easy */
07912    if (!strncasecmp(content_type, "application/sdp", 15)) {
07913       req->sdp_start = 0;
07914       req->sdp_count = req->lines;
07915       return req->lines ? 1 : 0;
07916    }
07917 
07918    /* if it's not multipart/mixed, there cannot be an SDP */
07919    if (strncasecmp(content_type, "multipart/mixed", 15))
07920       return 0;
07921 
07922    /* if there is no boundary marker, it's invalid */
07923    if ((search = strcasestr(content_type, ";boundary=")))
07924       search += 10;
07925    else if ((search = strcasestr(content_type, "; boundary=")))
07926       search += 11;
07927    else
07928       return 0;
07929 
07930    if (ast_strlen_zero(search))
07931       return 0;
07932 
07933    /* If the boundary is quoted with ", remove quote */
07934    if (*search == '\"')  {
07935       search++;
07936       boundaryisquoted = TRUE;
07937    }
07938 
07939    /* make a duplicate of the string, with two extra characters
07940       at the beginning */
07941    boundary = ast_strdupa(search - 2);
07942    boundary[0] = boundary[1] = '-';
07943    /* Remove final quote */
07944    if (boundaryisquoted)
07945       boundary[strlen(boundary) - 1] = '\0';
07946 
07947    /* search for the boundary marker, the empty line delimiting headers from
07948       sdp part and the end boundry if it exists */
07949 
07950    for (x = 0; x < (req->lines); x++) {
07951       char *line = REQ_OFFSET_TO_STR(req, line[x]);
07952       if (!strncasecmp(line, boundary, strlen(boundary))){
07953          if (found_application_sdp && found_end_of_headers) {
07954             req->sdp_count = (x - 1) - req->sdp_start;
07955             return 1;
07956          }
07957          found_application_sdp = FALSE;
07958       }
07959       if (!strcasecmp(line, "Content-Type: application/sdp"))
07960          found_application_sdp = TRUE;
07961       
07962       if (ast_strlen_zero(line)) {
07963          if (found_application_sdp && !found_end_of_headers){
07964             req->sdp_start = x;
07965             found_end_of_headers = TRUE;
07966          }
07967       }
07968    }
07969    if (found_application_sdp && found_end_of_headers) {
07970       req->sdp_count = x - req->sdp_start;
07971       return TRUE;
07972    }
07973    return FALSE;
07974 }
07975 
07976 enum media_type {
07977    SDP_AUDIO,
07978    SDP_VIDEO,
07979    SDP_IMAGE,
07980    SDP_TEXT,
07981 };
07982 
07983 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
07984 {
07985    const char *m;
07986    const char *c;
07987    int miterator = req->sdp_start;
07988    int citerator = req->sdp_start;
07989    int x = 0;
07990    int numberofports;
07991    int len;
07992    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
07993    struct ast_hostent audiohp;
07994    struct hostent *hp;
07995 
07996    c = get_sdp_iterate(&citerator, req, "c");
07997    if (sscanf(c, "IN IP4 %256s", host) != 1) {
07998       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07999       /* Continue since there may be a valid host in a c= line specific to the audio stream */
08000    }
08001    /* We only want the m and c lines for audio */
08002    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08003       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08004           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08005          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08006           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08007          /* See if there's a c= line for this media stream.
08008           * XXX There is no guarantee that we'll be grabbing the c= line for this
08009           * particular media stream here. However, this is the same logic used in process_sdp.
08010           */
08011          c = get_sdp_iterate(&citerator, req, "c");
08012          if (!ast_strlen_zero(c)) {
08013             sscanf(c, "IN IP4 %256s", host);
08014          }
08015          break;
08016       }
08017    }
08018 
08019    if (ast_strlen_zero(host) || x == 0) {
08020       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08021       return -1;
08022    }
08023 
08024    hp = ast_gethostbyname(host, &audiohp);
08025    if (!hp) {
08026       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08027       return -1;
08028    }
08029 
08030    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
08031    sin->sin_port = htons(x);
08032    return 0;
08033 }
08034 
08035 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
08036    If offer is rejected, we will not change any properties of the call
08037    Return 0 on success, a negative value on errors.
08038    Must be called after find_sdp().
08039 */
08040 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08041 {
08042    /* Iterators for SDP parsing */
08043    int start = req->sdp_start;
08044    int next = start;
08045    int iterator = start;
08046 
08047    /* Temporary vars for SDP parsing */
08048    char type = '\0';
08049    const char *value = NULL;
08050    const char *m = NULL;           /* SDP media offer */
08051    const char *nextm = NULL;
08052    int len = -1;
08053 
08054    /* Host information */
08055    struct ast_hostent sessionhp;
08056    struct ast_hostent audiohp;
08057    struct ast_hostent videohp;
08058    struct ast_hostent texthp;
08059    struct ast_hostent imagehp;
08060    struct hostent *hp = NULL; /*!< RTP Audio host IP */
08061    struct hostent *vhp = NULL;   /*!< RTP video host IP */
08062    struct hostent *thp = NULL;   /*!< RTP text host IP */
08063    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
08064    int portno = -1;     /*!< RTP Audio port number */
08065    int vportno = -1;    /*!< RTP Video port number */
08066    int tportno = -1;    /*!< RTP Text port number */
08067    int udptlportno = -1;      /*!< UDPTL Image port number */
08068    struct sockaddr_in sin;    /*!< media socket address */
08069    struct sockaddr_in vsin;   /*!< video socket address */
08070    struct sockaddr_in isin;   /*!< image socket address */
08071    struct sockaddr_in tsin;   /*!< text socket address */
08072 
08073    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
08074    int peercapability = 0, peernoncodeccapability = 0;
08075    int vpeercapability = 0, vpeernoncodeccapability = 0;
08076    int tpeercapability = 0, tpeernoncodeccapability = 0;
08077 
08078    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
08079    int newjointcapability;          /* Negotiated capability */
08080    int newpeercapability;
08081    int newnoncodeccapability;
08082 
08083    const char *codecs;
08084    int codec;
08085 
08086    /* Others */
08087    int sendonly = -1;
08088    int vsendonly = -1;
08089    int numberofports;
08090    int numberofmediastreams = 0;
08091    int last_rtpmap_codec = 0;
08092    int red_data_pt[10];    /* For T.140 red */
08093    int red_num_gen = 0;    /* For T.140 red */
08094    char red_fmtp[100] = "empty"; /* For T.140 red */
08095    int debug = sip_debug_test_pvt(p);
08096 
08097    /* START UNKNOWN */
08098    char buf[SIPBUFSIZE];
08099    /* END UNKNOWN */
08100 
08101    /* Initial check */
08102    if (!p->rtp) {
08103       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08104       return -1;
08105    }
08106 
08107    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
08108 #ifdef LOW_MEMORY
08109    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
08110 #else
08111    newaudiortp = alloca(ast_rtp_alloc_size());
08112 #endif
08113    memset(newaudiortp, 0, ast_rtp_alloc_size());
08114    ast_rtp_new_init(newaudiortp);
08115    ast_rtp_pt_clear(newaudiortp);
08116 
08117 #ifdef LOW_MEMORY
08118    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
08119 #else
08120    newvideortp = alloca(ast_rtp_alloc_size());
08121 #endif
08122    memset(newvideortp, 0, ast_rtp_alloc_size());
08123    ast_rtp_new_init(newvideortp);
08124    ast_rtp_pt_clear(newvideortp);
08125 
08126 #ifdef LOW_MEMORY
08127    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
08128 #else
08129    newtextrtp = alloca(ast_rtp_alloc_size());
08130 #endif
08131    memset(newtextrtp, 0, ast_rtp_alloc_size());
08132    ast_rtp_new_init(newtextrtp);
08133    ast_rtp_pt_clear(newtextrtp);
08134 
08135    /* Update our last rtprx when we receive an SDP, too */
08136    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08137 
08138    memset(p->offered_media, 0, sizeof(p->offered_media));
08139 
08140 
08141    /* default: novideo and notext set */
08142    p->novideo = TRUE;
08143    p->notext = TRUE;
08144 
08145    if (p->vrtp)
08146       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
08147  
08148    if (p->trtp)
08149       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
08150    
08151    /* Scan for the first media stream (m=) line to limit scanning of globals */
08152    nextm = get_sdp_iterate(&next, req, "m");
08153    if (ast_strlen_zero(nextm)) {
08154       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08155       return -1;
08156    }
08157 
08158    /* Scan session level SDP parameters (lines before first media stream) */
08159    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08160       int processed = FALSE;
08161       switch (type) {
08162       case 'o':
08163          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08164           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08165           */
08166          if (!process_sdp_o(value, p))
08167             return (p->session_modify == FALSE) ? 0 : -1;
08168          break;
08169       case 'c':
08170          if (process_sdp_c(value, &sessionhp)) {
08171             processed = TRUE;
08172             hp = &sessionhp.hp;
08173             vhp = hp;
08174             thp = hp;
08175             ihp = hp;
08176          }
08177          break;
08178       case 'a':
08179          if (process_sdp_a_sendonly(value, &sendonly)) {
08180             processed = TRUE;
08181             vsendonly = sendonly;
08182          }
08183          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08184             processed = TRUE;
08185          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08186             processed = TRUE;
08187          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08188             processed = TRUE;
08189          else if (process_sdp_a_image(value, p))
08190             processed = TRUE;
08191          break;
08192       }
08193 
08194       if (option_debug > 2)
08195          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
08196    }
08197 
08198 
08199 
08200    /* Scan media stream (m=) specific parameters loop */
08201    while (!ast_strlen_zero(nextm)) {
08202       int audio = FALSE;
08203       int video = FALSE;
08204       int image = FALSE;
08205       int text = FALSE;
08206       int x;
08207 
08208       numberofports = 1;
08209       len = -1;
08210       start = next;
08211       m = nextm;
08212       iterator = next;
08213       nextm = get_sdp_iterate(&next, req, "m");
08214 
08215       /* Search for audio media definition */
08216       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08217           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08218          audio = TRUE;
08219          p->offered_media[SDP_AUDIO].offered = TRUE;
08220          numberofmediastreams++;
08221          portno = x;
08222 
08223          /* Scan through the RTP payload types specified in a "m=" line: */
08224          codecs = m + len;
08225          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
08226          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08227             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08228                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08229                return -1;
08230             }
08231             if (debug)
08232                ast_verbose("Found RTP audio format %d\n", codec);
08233 
08234             ast_rtp_set_m_type(newaudiortp, codec);
08235          }
08236       /* Search for video media definition */
08237       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08238             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
08239          video = TRUE;
08240          p->novideo = FALSE;
08241          p->offered_media[SDP_VIDEO].offered = TRUE;
08242          numberofmediastreams++;
08243          vportno = x;
08244 
08245          /* Scan through the RTP payload types specified in a "m=" line: */
08246          codecs = m + len;
08247          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
08248          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08249             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08250                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08251                return -1;
08252             }
08253             if (debug)
08254                ast_verbose("Found RTP video format %d\n", codec);
08255             ast_rtp_set_m_type(newvideortp, codec);
08256          }
08257       /* Search for text media definition */
08258       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08259             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
08260          text = TRUE;
08261          p->notext = FALSE;
08262          p->offered_media[SDP_TEXT].offered = TRUE;
08263          numberofmediastreams++;
08264          tportno = x;
08265 
08266          /* Scan through the RTP payload types specified in a "m=" line: */
08267          codecs = m + len;
08268          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
08269          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
08270             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
08271                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
08272                return -1;
08273             }
08274             if (debug)
08275                ast_verbose("Found RTP text format %d\n", codec);
08276             ast_rtp_set_m_type(newtextrtp, codec);
08277          }
08278       /* Search for image media definition */
08279       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
08280                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
08281          image = TRUE;
08282          if (debug)
08283             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
08284          p->offered_media[SDP_IMAGE].offered = TRUE;
08285          udptlportno = x;
08286          numberofmediastreams++;
08287 
08288          if (p->t38.state != T38_ENABLED) {
08289             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
08290          }
08291       } else {
08292          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
08293          continue;
08294       }
08295 
08296       /* Check for number of ports */
08297       if (numberofports > 1)
08298          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
08299       
08300 
08301 
08302       /* Media stream specific parameters */
08303       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08304          int processed = FALSE;
08305 
08306          switch (type) {
08307          case 'c':
08308             if (audio) {
08309                if (process_sdp_c(value, &audiohp)) {
08310                   processed = TRUE;
08311                   hp = &audiohp.hp;
08312                }
08313             } else if (video) {
08314                if (process_sdp_c(value, &videohp)) {
08315                   processed = TRUE;
08316                   vhp = &videohp.hp;
08317                }
08318             } else if (text) {
08319                if (process_sdp_c(value, &texthp)) {
08320                   processed = TRUE;
08321                   thp = &texthp.hp;
08322                }
08323             } else if (image) {
08324                if (process_sdp_c(value, &imagehp)) {
08325                   processed = TRUE;
08326                   ihp = &imagehp.hp;
08327                }
08328             }
08329             break;
08330          case 'a':
08331             /* Audio specific scanning */
08332             if (audio) {
08333                if (process_sdp_a_sendonly(value, &sendonly))
08334                   processed = TRUE;
08335                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
08336                   processed = TRUE;
08337             }
08338             /* Video specific scanning */
08339             else if (video) {
08340                if (process_sdp_a_sendonly(value, &vsendonly))
08341                   processed = TRUE;
08342                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
08343                   processed = TRUE;
08344             }
08345             /* Text (T.140) specific scanning */
08346             else if (text) {
08347                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08348                   processed = TRUE;
08349             }
08350             /* Image (T.38 FAX) specific scanning */
08351             else if (image) {
08352                if (process_sdp_a_image(value, p))
08353                   processed = TRUE;
08354             }
08355             break;
08356          }
08357 
08358          if (option_debug > 2)
08359             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
08360                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
08361                   type, value,
08362                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
08363       }
08364    }
08365 
08366 
08367    /* Sanity checks */
08368    if (!hp && !vhp && !thp && !ihp) {
08369       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
08370       return -1;
08371    }
08372 
08373    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
08374       /* No acceptable offer found in SDP  - we have no ports */
08375       /* Do not change RTP or VRTP if this is a re-invite */
08376       return -2;
08377 
08378    if (numberofmediastreams > 3)
08379       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
08380       return -3;
08381 
08382    if (udptlportno == -1) {
08383       change_t38_state(p, T38_DISABLED);
08384    }
08385 
08386 
08387    /* Now gather all of the codecs that we are asked for: */
08388    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
08389    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
08390    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
08391 
08392    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
08393    newpeercapability = (peercapability | vpeercapability | tpeercapability);
08394    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
08395 
08396    if (debug) {
08397       /* shame on whoever coded this.... */
08398       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
08399 
08400       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
08401              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
08402              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
08403              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
08404              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
08405              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
08406 
08407       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
08408              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
08409              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
08410              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
08411    }
08412    if (!newjointcapability && (portno != -1)) {
08413       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
08414       /* Do NOT Change current setting */
08415       return -1;
08416    }
08417 
08418    /* Setup audio address and port */
08419    if (p->rtp) {
08420       if (portno > 0) {
08421          sin.sin_family = AF_INET;
08422          sin.sin_port = htons(portno);
08423          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
08424          ast_rtp_set_peer(p->rtp, &sin);
08425          if (debug)
08426             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
08427          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
08428             they are acceptable */
08429          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
08430          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
08431          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
08432 
08433          ast_rtp_pt_copy(p->rtp, newaudiortp);
08434 
08435          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
08436             ast_clear_flag(&p->flags[0], SIP_DTMF);
08437             if (newnoncodeccapability & AST_RTP_DTMF) {
08438                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
08439                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
08440                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
08441                ast_rtp_setdtmf(p->rtp, 1);
08442                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
08443             } else {
08444                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
08445             }
08446          }
08447       } else if (udptlportno > 0) {
08448          if (debug)
08449             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
08450       } else {
08451          ast_rtp_stop(p->rtp);
08452          if (debug)
08453             ast_verbose("Peer doesn't provide audio\n");
08454       }
08455    }
08456 
08457    /* Setup video address and port */
08458    if (p->vrtp) {
08459       if (vportno > 0) {
08460          vsin.sin_family = AF_INET;
08461          vsin.sin_port = htons(vportno);
08462          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
08463          ast_rtp_set_peer(p->vrtp, &vsin);
08464          if (debug) 
08465             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08466          ast_rtp_pt_copy(p->vrtp, newvideortp);
08467       } else {
08468          ast_rtp_stop(p->vrtp);
08469          if (debug)
08470             ast_verbose("Peer doesn't provide video\n");
08471       }
08472    }
08473 
08474    /* Setup text address and port */
08475    if (p->trtp) {
08476       if (tportno > 0) {
08477          tsin.sin_family = AF_INET;
08478          tsin.sin_port = htons(tportno);
08479          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
08480          ast_rtp_set_peer(p->trtp, &tsin);
08481          if (debug) 
08482             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
08483          if ((p->jointcapability & AST_FORMAT_T140RED)) {
08484             p->red = 1;
08485             rtp_red_init(p->trtp, 300, red_data_pt, 2);
08486          } else {
08487             p->red = 0;
08488          }
08489          ast_rtp_pt_copy(p->trtp, newtextrtp);
08490       } else {
08491          ast_rtp_stop(p->trtp);
08492          if (debug)
08493             ast_verbose("Peer doesn't provide T.140\n");
08494       }
08495    }
08496    /* Setup image address and port */
08497    if (p->udptl) {
08498       if (udptlportno > 0) {
08499          isin.sin_family = AF_INET;
08500          isin.sin_port = htons(udptlportno);
08501          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
08502             struct sockaddr_in remote_address = { 0, };
08503             ast_rtp_get_peer(p->rtp, &remote_address);
08504             if (remote_address.sin_addr.s_addr) {
08505                memcpy(&isin, &remote_address, sizeof(isin));
08506                if (debug) {
08507                   ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
08508                }
08509             }
08510          } else {
08511             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(sin.sin_addr));
08512          }
08513          ast_udptl_set_peer(p->udptl, &isin);
08514          if (debug)
08515             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
08516 
08517          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
08518          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
08519             /* setting to zero will force a default if none was provided by the SDP */
08520             ast_udptl_set_far_max_datagram(p->udptl, 0);
08521          }
08522 
08523          /* Remote party offers T38, we need to update state */
08524          if ((t38action == SDP_T38_ACCEPT) &&
08525              (p->t38.state == T38_LOCAL_REINVITE)) {
08526             change_t38_state(p, T38_ENABLED);
08527          } else if ((t38action == SDP_T38_INITIATE) &&
08528                p->owner && p->lastinvite) {
08529             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
08530          }
08531       } else {
08532          ast_udptl_stop(p->udptl);
08533          if (debug)
08534             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
08535       }
08536    }
08537 
08538    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
08539       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
08540                 return 0;
08541         }
08542 
08543    /* Ok, we're going with this offer */
08544    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
08545 
08546    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
08547       return 0;
08548 
08549    ast_debug(4, "We have an owner, now see if we need to change this call\n");
08550 
08551    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
08552       if (debug) {
08553          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
08554          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
08555             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
08556             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
08557       }
08558       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
08559       ast_set_read_format(p->owner, p->owner->readformat);
08560       ast_set_write_format(p->owner, p->owner->writeformat);
08561    }
08562    
08563    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
08564       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08565       /* Activate a re-invite */
08566       ast_queue_frame(p->owner, &ast_null_frame);
08567       /* Queue Manager Unhold event */
08568       append_history(p, "Unhold", "%s", req->data->str);
08569       if (sip_cfg.callevents)
08570          manager_event(EVENT_FLAG_CALL, "Hold",
08571                   "Status: Off\r\n"
08572                   "Channel: %s\r\n"
08573                   "Uniqueid: %s\r\n",
08574                   p->owner->name,
08575                   p->owner->uniqueid);
08576       if (sip_cfg.notifyhold)
08577          sip_peer_hold(p, FALSE);
08578       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
08579    } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
08580       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
08581       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
08582                    S_OR(p->mohsuggest, NULL),
08583                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08584       if (sendonly)
08585          ast_rtp_stop(p->rtp);
08586       /* RTCP needs to go ahead, even if we're on hold!!! */
08587       /* Activate a re-invite */
08588       ast_queue_frame(p->owner, &ast_null_frame);
08589       /* Queue Manager Hold event */
08590       append_history(p, "Hold", "%s", req->data->str);
08591       if (sip_cfg.callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08592          manager_event(EVENT_FLAG_CALL, "Hold",
08593                   "Status: On\r\n"
08594                   "Channel: %s\r\n"
08595                   "Uniqueid: %s\r\n",
08596                   p->owner->name, 
08597                   p->owner->uniqueid);
08598       }
08599       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08600          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08601       else if (sendonly == 2) /* Inactive stream */
08602          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08603       else
08604          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08605       if (sip_cfg.notifyhold && !already_on_hold)
08606          sip_peer_hold(p, TRUE);
08607    }
08608    
08609    return 0;
08610 }
08611 
08612 static int process_sdp_o(const char *o, struct sip_pvt *p)
08613 {
08614    char *o_copy;
08615    char *token;
08616    int64_t rua_version;
08617 
08618    /* Store the SDP version number of remote UA. This will allow us to
08619    distinguish between session modifications and session refreshes. If
08620    the remote UA does not send an incremented SDP version number in a
08621    subsequent RE-INVITE then that means its not changing media session.
08622    The RE-INVITE may have been sent to update connected party, remote
08623    target or to refresh the session (Session-Timers).  Asterisk must not
08624    change media session and increment its own version number in answer
08625    SDP in this case. */
08626 
08627    p->session_modify = TRUE;
08628 
08629    if (ast_strlen_zero(o)) {
08630       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08631       return FALSE;
08632    }
08633 
08634    o_copy = ast_strdupa(o);
08635    token = strsep(&o_copy, " ");  /* Skip username   */
08636    if (!o_copy) {
08637       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08638       return FALSE;
08639    }
08640    token = strsep(&o_copy, " ");  /* Skip session-id */
08641    if (!o_copy) {
08642       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08643       return FALSE;
08644    }
08645    token = strsep(&o_copy, " ");  /* Version         */
08646    if (!o_copy) {
08647       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08648       return FALSE;
08649    }
08650    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08651       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08652       return FALSE;
08653    }
08654 
08655    /* we need to check the SDP version number the other end sent us;
08656     * our rules for deciding what to accept are a bit complex.
08657     *
08658     * 1) if 'ignoresdpversion' has been set for this dialog, then
08659     *    we will just accept whatever they sent and assume it is
08660     *    a modification of the session, even if it is not
08661     * 2) otherwise, if this is the first SDP we've seen from them
08662     *    we accept it
08663     * 3) otherwise, if the new SDP version number is higher than the
08664     *    old one, we accept it
08665     * 4) otherwise, if this SDP is in response to us requesting a switch
08666     *    to T.38, we accept the SDP, but also generate a warning message
08667     *    that this peer should have the 'ignoresdpversion' option set,
08668     *    because it is not following the SDP offer/answer RFC; if we did
08669     *    not request a switch to T.38, then we stop parsing the SDP, as it
08670     *    has not changed from the previous version
08671     */
08672 
08673    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08674        (p->sessionversion_remote < 0) ||
08675        (p->sessionversion_remote < rua_version)) {
08676       p->sessionversion_remote = rua_version;
08677    } else {
08678       if (p->t38.state == T38_LOCAL_REINVITE) {
08679          p->sessionversion_remote = rua_version;
08680          ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
08681       } else {
08682          p->session_modify = FALSE;
08683          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08684          return FALSE;
08685       }
08686    }
08687 
08688    return TRUE;
08689 }
08690 
08691 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08692 {
08693    char host[258];
08694    struct hostent *hp;
08695 
08696    /* Check for Media-description-level-address */
08697    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08698       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08699       return FALSE;
08700    } else {
08701       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08702          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08703          return FALSE;
08704       }
08705       return TRUE;
08706    }
08707    return FALSE;
08708 }
08709 
08710 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08711 {
08712    int found = FALSE;
08713 
08714    if (!strcasecmp(a, "sendonly")) {
08715       if (*sendonly == -1)
08716          *sendonly = 1;
08717       found = TRUE;
08718    } else if (!strcasecmp(a, "inactive")) {
08719       if (*sendonly == -1)
08720          *sendonly = 2;
08721       found = TRUE;
08722    }  else if (!strcasecmp(a, "sendrecv")) {
08723       if (*sendonly == -1)
08724          *sendonly = 0;
08725       found = TRUE;
08726    }
08727    return found;
08728 }
08729 
08730 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08731 {
08732    int found = FALSE;
08733    int codec;
08734    char mimeSubtype[128];
08735    char fmtp_string[64];
08736    unsigned int sample_rate;
08737    int debug = sip_debug_test_pvt(p);
08738 
08739    if (!strncasecmp(a, "ptime", 5)) {
08740       char *tmp = strrchr(a, ':');
08741       long int framing = 0;
08742       if (tmp) {
08743          tmp++;
08744          framing = strtol(tmp, NULL, 10);
08745          if (framing == LONG_MIN || framing == LONG_MAX) {
08746             framing = 0;
08747             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08748          }
08749       }
08750       if (framing && p->autoframing) {
08751          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08752          int codec_n;
08753          int format = 0;
08754          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08755             format = ast_rtp_codec_getformat(codec_n);
08756             if (!format)   /* non-codec or not found */
08757                continue;
08758             if (option_debug)
08759                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08760             ast_codec_pref_setsize(pref, format, framing);
08761          }
08762          ast_rtp_codec_setpref(p->rtp, pref);
08763       }
08764       found = TRUE;
08765    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08766       /* We have a rtpmap to handle */
08767       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08768          if (ast_rtp_set_rtpmap_type_rate(newaudiortp, codec, "audio", mimeSubtype,
08769              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate) != -1) {
08770             if (debug)
08771                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08772             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08773             (*last_rtpmap_codec)++;
08774             found = TRUE;
08775          } else {
08776             ast_rtp_unset_m_type(newaudiortp, codec);
08777             if (debug)
08778                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08779          }
08780       } else {
08781          if (debug)
08782             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08783       }
08784    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
08785       struct rtpPayloadType payload;
08786 
08787       payload = ast_rtp_lookup_pt(newaudiortp, codec);
08788       if (payload.code && payload.isAstFormat) {
08789          unsigned int bit_rate;
08790 
08791          switch (payload.code) {
08792          case AST_FORMAT_SIREN7:
08793             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08794                if (bit_rate != 32000) {
08795                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
08796                   ast_rtp_unset_m_type(newaudiortp, codec);
08797                } else {
08798                   found = TRUE;
08799                }
08800             }
08801             break;
08802          case AST_FORMAT_SIREN14:
08803             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
08804                if (bit_rate != 48000) {
08805                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
08806                   ast_rtp_unset_m_type(newaudiortp, codec);
08807                } else {
08808                   found = TRUE;
08809                }
08810             }
08811             break;
08812          }
08813       }
08814    }
08815 
08816    return found;
08817 }
08818 
08819 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08820 {
08821    int found = FALSE;
08822    int codec;
08823    char mimeSubtype[128];
08824    unsigned int sample_rate;
08825    int debug = sip_debug_test_pvt(p);
08826 
08827    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08828       /* We have a rtpmap to handle */
08829       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08830          /* Note: should really look at the '#chans' params too */
08831          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08832             if (ast_rtp_set_rtpmap_type_rate(newvideortp, codec, "video", mimeSubtype, 0, sample_rate) != -1) {
08833                if (debug)
08834                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08835                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08836                (*last_rtpmap_codec)++;
08837                found = TRUE;
08838             } else {
08839                ast_rtp_unset_m_type(newvideortp, codec);
08840                if (debug) 
08841                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08842             }
08843          }
08844       } else {
08845          if (debug)
08846             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08847       }
08848    }
08849 
08850    return found;
08851 }
08852 
08853 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
08854 {
08855    int found = FALSE;
08856    int codec;
08857    char mimeSubtype[128];
08858    unsigned int sample_rate;
08859    char *red_cp;
08860    int debug = sip_debug_test_pvt(p);
08861 
08862    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
08863       /* We have a rtpmap to handle */
08864       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08865          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08866             if (p->trtp) {
08867                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08868                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08869                found = TRUE;
08870             }
08871          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08872             if (p->trtp) {
08873                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08874                sprintf(red_fmtp, "fmtp:%d ", codec); 
08875                if (debug)
08876                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08877                found = TRUE;
08878             }
08879          }
08880       } else {
08881          if (debug)
08882             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08883       }
08884    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08885       /* count numbers of generations in fmtp */
08886       red_cp = &red_fmtp[strlen(red_fmtp)];
08887       strncpy(red_fmtp, a, 100);
08888 
08889       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08890       red_cp = strtok(red_cp, "/");
08891       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08892          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08893          red_cp = strtok(NULL, "/");
08894       }
08895       red_cp = red_fmtp;
08896       found = TRUE;
08897    }
08898 
08899    return found;
08900 }
08901 
08902 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08903 {
08904    int found = FALSE;
08905    char s[256];
08906    unsigned int x;
08907 
08908    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08909       ast_debug(3, "MaxBufferSize:%d\n", x);
08910       found = TRUE;
08911    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08912       ast_debug(3, "T38MaxBitRate: %d\n", x);
08913       switch (x) {
08914       case 14400:
08915          p->t38.their_parms.rate = AST_T38_RATE_14400;
08916          break;
08917       case 12000:
08918          p->t38.their_parms.rate = AST_T38_RATE_12000;
08919          break;
08920       case 9600:
08921          p->t38.their_parms.rate = AST_T38_RATE_9600;
08922          break;
08923       case 7200:
08924          p->t38.their_parms.rate = AST_T38_RATE_7200;
08925          break;
08926       case 4800:
08927          p->t38.their_parms.rate = AST_T38_RATE_4800;
08928          break;
08929       case 2400:
08930          p->t38.their_parms.rate = AST_T38_RATE_2400;
08931          break;
08932       }
08933       found = TRUE;
08934    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08935       ast_debug(3, "FaxVersion: %u\n", x);
08936       p->t38.their_parms.version = x;
08937       found = TRUE;
08938    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08939       /* override the supplied value if the configuration requests it */
08940       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
08941          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08942          x = p->t38_maxdatagram;
08943       }
08944       ast_debug(3, "FaxMaxDatagram: %u\n", x);
08945       ast_udptl_set_far_max_datagram(p->udptl, x);
08946       found = TRUE;
08947    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08948       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08949          ast_debug(3, "FillBitRemoval: %d\n", x);
08950          if (x == 1) {
08951             p->t38.their_parms.fill_bit_removal = TRUE;
08952          }
08953       } else {
08954          ast_debug(3, "FillBitRemoval\n");
08955          p->t38.their_parms.fill_bit_removal = TRUE;
08956       }
08957       found = TRUE;
08958    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
08959       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
08960          ast_debug(3, "Transcoding MMR: %d\n", x);
08961          if (x == 1) {
08962             p->t38.their_parms.transcoding_mmr = TRUE;
08963          }
08964       } else {
08965          ast_debug(3, "Transcoding MMR\n");
08966          p->t38.their_parms.transcoding_mmr = TRUE;
08967       }
08968       found = TRUE;
08969    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
08970       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
08971          ast_debug(3, "Transcoding JBIG: %d\n", x);
08972          if (x == 1) {
08973             p->t38.their_parms.transcoding_jbig = TRUE;
08974          }
08975       } else {
08976          ast_debug(3, "Transcoding JBIG\n");
08977          p->t38.their_parms.transcoding_jbig = TRUE;
08978       }
08979       found = TRUE;
08980    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
08981       ast_debug(3, "RateManagement: %s\n", s);
08982       if (!strcasecmp(s, "localTCF"))
08983          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
08984       else if (!strcasecmp(s, "transferredTCF"))
08985          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
08986       found = TRUE;
08987    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
08988       ast_debug(3, "UDP EC: %s\n", s);
08989       if (!strcasecmp(s, "t38UDPRedundancy")) {
08990          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
08991       } else if (!strcasecmp(s, "t38UDPFEC")) {
08992          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
08993       } else {
08994          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08995       }
08996       found = TRUE;
08997    }
08998 
08999    return found;
09000 }
09001 
09002 
09003 #ifdef LOW_MEMORY
09004 static void ts_ast_rtp_destroy(void *data)
09005 {
09006     struct ast_rtp *tmp = data;
09007     ast_rtp_destroy(tmp);
09008 }
09009 #endif
09010 
09011 /*! \brief Add header to SIP message */
09012 static int add_header(struct sip_request *req, const char *var, const char *value)
09013 {
09014    if (req->headers == SIP_MAX_HEADERS) {
09015       ast_log(LOG_WARNING, "Out of SIP header space\n");
09016       return -1;
09017    }
09018 
09019    if (req->lines) {
09020       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09021       return -1;
09022    }
09023 
09024    if (sip_cfg.compactheaders) {
09025       var = find_alias(var, var);
09026    }
09027 
09028    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09029    req->header[req->headers] = req->len;
09030 
09031    req->len = ast_str_strlen(req->data);
09032    req->headers++;
09033 
09034    return 0;   
09035 }
09036 
09037 /*! \brief Add 'Content-Length' header to SIP message */
09038 static int add_header_contentLength(struct sip_request *req, int len)
09039 {
09040    char clen[10];
09041 
09042    snprintf(clen, sizeof(clen), "%d", len);
09043    return add_header(req, "Content-Length", clen);
09044 }
09045 
09046 /*! \brief Add content (not header) to SIP message */
09047 static int add_line(struct sip_request *req, const char *line)
09048 {
09049    if (req->lines == SIP_MAX_LINES)  {
09050       ast_log(LOG_WARNING, "Out of SIP line space\n");
09051       return -1;
09052    }
09053    if (!req->lines)
09054       /* Add extra empty return */
09055       req->len += ast_str_append(&req->data, 0, "\r\n");
09056    req->line[req->lines] = req->len;
09057    ast_str_append(&req->data, 0, "%s", line);
09058    req->len = ast_str_strlen(req->data);
09059    req->lines++;
09060    return 0;   
09061 }
09062 
09063 /*! \brief Copy one header field from one request to another */
09064 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09065 {
09066    const char *tmp = get_header(orig, field);
09067 
09068    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
09069       return add_header(req, field, tmp);
09070    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
09071    return -1;
09072 }
09073 
09074 /*! \brief Copy all headers from one request to another */
09075 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
09076 {
09077    int start = 0;
09078    int copied = 0;
09079    for (;;) {
09080       const char *tmp = __get_header(orig, field, &start);
09081 
09082       if (ast_strlen_zero(tmp))
09083          break;
09084       /* Add what we're responding to */
09085       add_header(req, field, tmp);
09086       copied++;
09087    }
09088    return copied ? 0 : -1;
09089 }
09090 
09091 /*! \brief Copy SIP VIA Headers from the request to the response
09092 \note If the client indicates that it wishes to know the port we received from,
09093    it adds ;rport without an argument to the topmost via header. We need to
09094    add the port number (from our point of view) to that parameter.
09095 \verbatim
09096    We always add ;received=<ip address> to the topmost via header.
09097 \endverbatim
09098    Received: RFC 3261, rport RFC 3581 */
09099 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
09100 {
09101    int copied = 0;
09102    int start = 0;
09103 
09104    for (;;) {
09105       char new[512];
09106       const char *oh = __get_header(orig, field, &start);
09107 
09108       if (ast_strlen_zero(oh))
09109          break;
09110 
09111       if (!copied) { /* Only check for empty rport in topmost via header */
09112          char leftmost[512], *others, *rport;
09113 
09114          /* Only work on leftmost value */
09115          ast_copy_string(leftmost, oh, sizeof(leftmost));
09116          others = strchr(leftmost, ',');
09117          if (others)
09118              *others++ = '\0';
09119 
09120          /* Find ;rport;  (empty request) */
09121          rport = strstr(leftmost, ";rport");
09122          if (rport && *(rport+6) == '=') 
09123             rport = NULL;     /* We already have a parameter to rport */
09124 
09125          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
09126          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
09127             /* We need to add received port - rport */
09128             char *end;
09129 
09130             rport = strstr(leftmost, ";rport");
09131 
09132             if (rport) {
09133                end = strchr(rport + 1, ';');
09134                if (end)
09135                   memmove(rport, end, strlen(end) + 1);
09136                else
09137                   *rport = '\0';
09138             }
09139 
09140             /* Add rport to first VIA header if requested */
09141             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
09142                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09143                ntohs(p->recv.sin_port),
09144                others ? "," : "", others ? others : "");
09145          } else {
09146             /* We should *always* add a received to the topmost via */
09147             snprintf(new, sizeof(new), "%s;received=%s%s%s",
09148                leftmost, ast_inet_ntoa(p->recv.sin_addr),
09149                others ? "," : "", others ? others : "");
09150          }
09151          oh = new;   /* the header to copy */
09152       }  /* else add the following via headers untouched */
09153       add_header(req, field, oh);
09154       copied++;
09155    }
09156    if (!copied) {
09157       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
09158       return -1;
09159    }
09160    return 0;
09161 }
09162 
09163 /*! \brief Add route header into request per learned route */
09164 static void add_route(struct sip_request *req, struct sip_route *route)
09165 {
09166    char r[SIPBUFSIZE*2], *p;
09167    int n, rem = sizeof(r);
09168 
09169    if (!route)
09170       return;
09171 
09172    p = r;
09173    for (;route ; route = route->next) {
09174       n = strlen(route->hop);
09175       if (rem < n+3) /* we need room for ",<route>" */
09176          break;
09177       if (p != r) {  /* add a separator after fist route */
09178          *p++ = ',';
09179          --rem;
09180       }
09181       *p++ = '<';
09182       ast_copy_string(p, route->hop, rem); /* cannot fail */
09183       p += n;
09184       *p++ = '>';
09185       rem -= (n+2);
09186    }
09187    *p = '\0';
09188    add_header(req, "Route", r);
09189 }
09190 
09191 /*! \brief Set destination from SIP URI 
09192  *
09193  * Parse uri to h (host) and port - uri is already just the part inside the <> 
09194  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
09195  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
09196  * for SIP: uri's
09197  *
09198  * If there's a sips: uri scheme, TLS will be required. 
09199  */
09200 static void set_destination(struct sip_pvt *p, char *uri)
09201 {
09202    char *h, *maddr, hostname[256];
09203    int port, hn;
09204    struct hostent *hp;
09205    struct ast_hostent ahp;
09206    int debug=sip_debug_test_pvt(p);
09207    int tls_on = FALSE;
09208    int use_dns = sip_cfg.srvlookup;
09209 
09210    if (debug)
09211       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
09212 
09213    /* Find and parse hostname */
09214    h = strchr(uri, '@');
09215    if (h)
09216       ++h;
09217    else {
09218       h = uri;
09219       if (!strncasecmp(h, "sip:", 4)) {
09220          h += 4;
09221       } else if (!strncasecmp(h, "sips:", 5)) {
09222          h += 5;
09223          tls_on = TRUE;
09224       }
09225    }
09226    hn = strcspn(h, ":;>") + 1;
09227    if (hn > sizeof(hostname)) 
09228       hn = sizeof(hostname);
09229    ast_copy_string(hostname, h, hn);
09230    /* XXX bug here if string has been trimmed to sizeof(hostname) */
09231    h += hn - 1;
09232 
09233    /* Is "port" present? if not default to STANDARD_SIP_PORT */
09234    if (*h == ':') {
09235       /* Parse port */
09236       ++h;
09237       port = strtol(h, &h, 10);
09238       use_dns = FALSE;
09239    } else
09240       port = tls_on ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
09241 
09242    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
09243    maddr = strstr(h, "maddr=");
09244    if (maddr) {
09245       maddr += 6;
09246       hn = strspn(maddr, "0123456789.") + 1;
09247       if (hn > sizeof(hostname))
09248          hn = sizeof(hostname);
09249       ast_copy_string(hostname, maddr, hn);
09250    }
09251 
09252    /*! \todo XXX If we have use_dns on, then look for NAPTR/SRV, otherwise, just look for A records */
09253    
09254    hp = ast_gethostbyname(hostname, &ahp);
09255    if (hp == NULL)  {
09256       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
09257       return;
09258    }
09259    p->sa.sin_family = AF_INET;
09260    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
09261    p->sa.sin_port = htons(port);
09262    if (debug)
09263       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
09264 }
09265 
09266 /*! \brief Initialize SIP response, based on SIP request */
09267 static int init_resp(struct sip_request *resp, const char *msg)
09268 {
09269    /* Initialize a response */
09270    memset(resp, 0, sizeof(*resp));
09271    resp->method = SIP_RESPONSE;
09272    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
09273       return -1;
09274    resp->header[0] = 0;
09275    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
09276    resp->len = resp->data->used;
09277    resp->headers++;
09278    return 0;
09279 }
09280 
09281 /*! \brief Initialize SIP request */
09282 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
09283 {
09284    /* Initialize a request */
09285    memset(req, 0, sizeof(*req));
09286    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
09287       return -1;
09288    req->method = sipmethod;
09289    req->header[0] = 0;
09290    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
09291    req->len = ast_str_strlen(req->data);
09292    req->headers++;
09293    return 0;
09294 }
09295 
09296 /*! \brief Test if this response needs a contact header */
09297 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
09298    /* Requirements for Contact header inclusion in responses generated
09299     * from the header tables found in the following RFCs.  Where the
09300     * Contact header was marked mandatory (m) or optional (o) this
09301     * function returns 1.
09302     *
09303     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
09304     * - RFC 2976 (INFO)
09305     * - RFC 3262 (PRACK)
09306     * - RFC 3265 (SUBSCRIBE, NOTIFY)
09307     * - RFC 3311 (UPDATE)
09308     * - RFC 3428 (MESSAGE)
09309     * - RFC 3515 (REFER)
09310     * - RFC 3903 (PUBLISH)
09311     */
09312 
09313    switch (method) {
09314       /* 1xx, 2xx, 3xx, 485 */
09315       case SIP_INVITE:
09316       case SIP_UPDATE:
09317       case SIP_SUBSCRIBE:
09318       case SIP_NOTIFY:
09319          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
09320             return 1;
09321          break;
09322 
09323       /* 2xx, 3xx, 485 */
09324       case SIP_REGISTER:
09325       case SIP_OPTIONS:
09326          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
09327             return 1;
09328          break;
09329 
09330       /* 3xx, 485 */
09331       case SIP_BYE:
09332       case SIP_PRACK:
09333       case SIP_MESSAGE:
09334       case SIP_PUBLISH:
09335          if (msg[0] == '3' || !strncmp(msg, "485", 3))
09336             return 1;
09337          break;
09338 
09339       /* 2xx, 3xx, 4xx, 5xx, 6xx */
09340       case SIP_REFER:
09341          if (msg[0] >= '2' && msg[0] <= '6')
09342             return 1;
09343          break;
09344 
09345       /* contact will not be included for everything else */
09346       case SIP_ACK:
09347       case SIP_CANCEL:
09348       case SIP_INFO:
09349       case SIP_PING:
09350       default:
09351          return 0;
09352    }
09353    return 0;
09354 }
09355 
09356 /*! \brief Prepare SIP response packet */
09357 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
09358 {
09359    char newto[256];
09360    const char *ot;
09361 
09362    init_resp(resp, msg);
09363    copy_via_headers(p, resp, req, "Via");
09364    if (msg[0] == '1' || msg[0] == '2')
09365       copy_all_header(resp, req, "Record-Route");
09366    copy_header(resp, req, "From");
09367    ot = get_header(req, "To");
09368    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
09369       /* Add the proper tag if we don't have it already.  If they have specified
09370          their tag, use it.  Otherwise, use our own tag */
09371       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
09372          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09373       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
09374          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09375       else
09376          ast_copy_string(newto, ot, sizeof(newto));
09377       ot = newto;
09378    }
09379    add_header(resp, "To", ot);
09380    copy_header(resp, req, "Call-ID");
09381    copy_header(resp, req, "CSeq");
09382    if (!ast_strlen_zero(global_useragent))
09383       add_header(resp, "Server", global_useragent);
09384    add_header(resp, "Allow", ALLOWED_METHODS);
09385    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
09386 
09387    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
09388    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
09389       char se_hdr[256];
09390       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09391          strefresher2str(p->stimer->st_ref));
09392       add_header(resp, "Require", "timer");
09393       add_header(resp, "Session-Expires", se_hdr);
09394    }
09395 
09396    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
09397       /* For registration responses, we also need expiry and
09398          contact info */
09399       char tmp[256];
09400 
09401       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
09402       add_header(resp, "Expires", tmp);
09403       if (p->expiry) {  /* Only add contact if we have an expiry time */
09404          char contact[SIPBUFSIZE];
09405          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
09406          char *brackets = strchr(contact_uri, '<');
09407          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
09408          add_header(resp, "Contact", contact);  /* Not when we unregister */
09409       }
09410    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
09411       add_header(resp, "Contact", p->our_contact);
09412    }
09413 
09414    if (!ast_strlen_zero(p->url)) {
09415       add_header(resp, "Access-URL", p->url);
09416       ast_string_field_set(p, url, NULL);
09417    }
09418 
09419    return 0;
09420 }
09421 
09422 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
09423 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
09424 {
09425    struct sip_request *orig = &p->initreq;
09426    char stripped[80];
09427    char tmp[80];
09428    char newto[256];
09429    const char *c;
09430    const char *ot, *of;
09431    int is_strict = FALSE;     /*!< Strict routing flag */
09432    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
09433 
09434    memset(req, 0, sizeof(struct sip_request));
09435    
09436    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
09437    
09438    if (!seqno) {
09439       p->ocseq++;
09440       seqno = p->ocseq;
09441    }
09442    
09443    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
09444    if (sipmethod == SIP_CANCEL) {
09445       p->branch = p->invite_branch;
09446       build_via(p);
09447    } else if (newbranch && (sipmethod == SIP_INVITE)) {
09448       p->branch ^= ast_random();
09449       p->invite_branch = p->branch;
09450       build_via(p);
09451    } else if (newbranch) {
09452       p->branch ^= ast_random();
09453       build_via(p);
09454    }
09455 
09456    /* Check for strict or loose router */
09457    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
09458       is_strict = TRUE;
09459       if (sipdebug)
09460          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
09461    }
09462    
09463    if (sipmethod == SIP_CANCEL)
09464       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
09465    else if (sipmethod == SIP_ACK) {
09466       /* Use URI from Contact: in 200 OK (if INVITE) 
09467       (we only have the contacturi on INVITEs) */
09468       if (!ast_strlen_zero(p->okcontacturi))
09469          c = is_strict ? p->route->hop : p->okcontacturi;
09470       else
09471          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
09472    } else if (!ast_strlen_zero(p->okcontacturi)) 
09473       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
09474    else if (!ast_strlen_zero(p->uri)) 
09475       c = p->uri;
09476    else {
09477       char *n;
09478       /* We have no URI, use To: or From:  header as URI (depending on direction) */
09479       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
09480             sizeof(stripped));
09481       n = get_in_brackets(stripped);
09482       c = remove_uri_parameters(n);
09483    }  
09484    init_req(req, sipmethod, c);
09485 
09486    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
09487 
09488    add_header(req, "Via", p->via);
09489    if (p->route) {
09490       set_destination(p, p->route->hop);
09491       add_route(req, is_strict ? p->route->next : p->route);
09492    }
09493    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
09494 
09495    ot = get_header(orig, "To");
09496    of = get_header(orig, "From");
09497 
09498    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
09499       as our original request, including tag (or presumably lack thereof) */
09500    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
09501       /* Add the proper tag if we don't have it already.  If they have specified
09502          their tag, use it.  Otherwise, use our own tag */
09503       if (is_outbound && !ast_strlen_zero(p->theirtag))
09504          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
09505       else if (!is_outbound)
09506          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
09507       else
09508          snprintf(newto, sizeof(newto), "%s", ot);
09509       ot = newto;
09510    }
09511 
09512    if (is_outbound) {
09513       add_header(req, "From", of);
09514       add_header(req, "To", ot);
09515    } else {
09516       add_header(req, "From", ot);
09517       add_header(req, "To", of);
09518    }
09519    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
09520    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
09521       add_header(req, "Contact", p->our_contact);
09522 
09523    copy_header(req, orig, "Call-ID");
09524    add_header(req, "CSeq", tmp);
09525 
09526    if (!ast_strlen_zero(global_useragent))
09527       add_header(req, "User-Agent", global_useragent);
09528 
09529    if (!ast_strlen_zero(p->rpid))
09530       add_header(req, "Remote-Party-ID", p->rpid);
09531 
09532    if (!ast_strlen_zero(p->url)) {
09533       add_header(req, "Access-URL", p->url);
09534       ast_string_field_set(p, url, NULL);
09535    }
09536 
09537    /* Add Session-Timers related headers if the feature is active for this session.
09538       An exception to this behavior is the ACK request. Since Asterisk never requires 
09539       session-timers support from a remote end-point (UAS) in an INVITE, it must 
09540       not send 'Require: timer' header in the ACK request. 
09541       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
09542       in-dialog messages.
09543    */
09544    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
09545        && sipmethod == SIP_INVITE) {
09546       char se_hdr[256];
09547       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
09548          strefresher2str(p->stimer->st_ref));
09549       add_header(req, "Require", "timer");
09550       add_header(req, "Session-Expires", se_hdr);
09551       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
09552       add_header(req, "Min-SE", se_hdr);
09553    }
09554 
09555    return 0;
09556 }
09557 
09558 /*! \brief Base transmit response function */
09559 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09560 {
09561    struct sip_request resp;
09562    int seqno = 0;
09563 
09564    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09565       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09566       return -1;
09567    }
09568    respprep(&resp, p, msg, req);
09569    add_header_contentLength(&resp, 0);
09570    /* If we are cancelling an incoming invite for some reason, add information
09571       about the reason why we are doing this in clear text */
09572    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
09573       char buf[10];
09574 
09575       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
09576       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
09577       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
09578    }
09579    return send_response(p, &resp, reliable, seqno);
09580 }
09581 
09582 static int temp_pvt_init(void *data)
09583 {
09584    struct sip_pvt *p = data;
09585 
09586    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
09587    return ast_string_field_init(p, 512);
09588 }
09589 
09590 static void temp_pvt_cleanup(void *data)
09591 {
09592    struct sip_pvt *p = data;
09593 
09594    ast_string_field_free_memory(p);
09595 
09596    ast_free(data);
09597 }
09598 
09599 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
09600 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg)
09601 {
09602    struct sip_pvt *p = NULL;
09603 
09604    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
09605       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
09606       return -1;
09607    }
09608 
09609    /* XXX the structure may be dirty from previous usage.
09610     * Here we should state clearly how we should reinitialize it
09611     * before using it.
09612     * E.g. certainly the threadstorage should be left alone,
09613     * but other thihngs such as flags etc. maybe need cleanup ?
09614     */
09615     
09616    /* Initialize the bare minimum */
09617    p->method = intended_method;
09618 
09619    if (!sin)
09620       p->ourip = internip;
09621    else {
09622       p->sa = *sin;
09623       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
09624    }
09625 
09626    p->branch = ast_random();
09627    make_our_tag(p->tag, sizeof(p->tag));
09628    p->ocseq = INITIAL_CSEQ;
09629 
09630    if (useglobal_nat && sin) {
09631       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09632       p->recv = *sin;
09633       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09634    }
09635 
09636    ast_string_field_set(p, fromdomain, default_fromdomain);
09637    build_via(p);
09638    ast_string_field_set(p, callid, callid);
09639 
09640    copy_socket_data(&p->socket, &req->socket);
09641 
09642    /* Use this temporary pvt structure to send the message */
09643    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09644 
09645    /* Free the string fields, but not the pool space */
09646    ast_string_field_init(p, 0);
09647 
09648    return 0;
09649 }
09650 
09651 /*! \brief Transmit response, no retransmits */
09652 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09653 {
09654    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09655 }
09656 
09657 /*! \brief Transmit response, no retransmits */
09658 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09659 {
09660    struct sip_request resp;
09661    respprep(&resp, p, msg, req);
09662    append_date(&resp);
09663    add_header(&resp, "Unsupported", unsupported);
09664    add_header_contentLength(&resp, 0);
09665    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09666 }
09667 
09668 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09669 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09670 {
09671    struct sip_request resp;
09672    char minse_str[20];
09673 
09674    respprep(&resp, p, msg, req);
09675    append_date(&resp);
09676 
09677    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09678    add_header(&resp, "Min-SE", minse_str);
09679 
09680    add_header_contentLength(&resp, 0);
09681    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09682 }
09683 
09684 
09685 /*! \brief Transmit response, Make sure you get an ACK
09686    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09687 */
09688 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09689 {
09690    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09691 }
09692 
09693 /*! \brief Append date to SIP message */
09694 static void append_date(struct sip_request *req)
09695 {
09696    char tmpdat[256];
09697    struct tm tm;
09698    time_t t = time(NULL);
09699 
09700    gmtime_r(&t, &tm);
09701    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09702    add_header(req, "Date", tmpdat);
09703 }
09704 
09705 /*! \brief Append date and content length before transmitting response */
09706 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09707 {
09708    struct sip_request resp;
09709    respprep(&resp, p, msg, req);
09710    append_date(&resp);
09711    add_header_contentLength(&resp, 0);
09712    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09713 }
09714 
09715 /*! \brief Append Accept header, content length before transmitting response */
09716 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09717 {
09718    struct sip_request resp;
09719    respprep(&resp, p, msg, req);
09720    add_header(&resp, "Accept", "application/sdp");
09721    add_header_contentLength(&resp, 0);
09722    return send_response(p, &resp, reliable, 0);
09723 }
09724 
09725 /*! \brief Respond with authorization request */
09726 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
09727 {
09728    struct sip_request resp;
09729    char tmp[512];
09730    int seqno = 0;
09731 
09732    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09733       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09734       return -1;
09735    }
09736    /* Stale means that they sent us correct authentication, but 
09737       based it on an old challenge (nonce) */
09738    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", sip_cfg.realm, randdata, stale ? ", stale=true" : "");
09739    respprep(&resp, p, msg, req);
09740    add_header(&resp, header, tmp);
09741    add_header_contentLength(&resp, 0);
09742    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09743    return send_response(p, &resp, reliable, seqno);
09744 }
09745 
09746 /* Only use a static string for the msg, here! */
09747 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09748 {
09749    int res;
09750 
09751    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09752       p->last_provisional = msg;
09753       update_provisional_keepalive(p, with_sdp);
09754    }
09755 
09756    return res;
09757 }
09758 
09759 /*! \brief Add text body to SIP message */
09760 static int add_text(struct sip_request *req, const char *text)
09761 {
09762    /* XXX Convert \n's to \r\n's XXX */
09763    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09764    add_header_contentLength(req, strlen(text));
09765    add_line(req, text);
09766    return 0;
09767 }
09768 
09769 /*! \brief Add DTMF INFO tone to sip message 
09770    Mode =   0 for application/dtmf-relay (Cisco)
09771       1 for application/dtmf
09772 */
09773 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09774 {
09775    char tmp[256];
09776    int event;
09777    if (mode) {
09778       /* Application/dtmf short version used by some implementations */
09779       if (digit == '*')
09780          event = 10;
09781       else if (digit == '#')
09782          event = 11;
09783       else if ((digit >= 'A') && (digit <= 'D'))
09784          event = 12 + digit - 'A';
09785       else
09786          event = atoi(&digit);
09787       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09788       add_header(req, "Content-Type", "application/dtmf");
09789       add_header_contentLength(req, strlen(tmp));
09790       add_line(req, tmp);
09791    } else {
09792       /* Application/dtmf-relay as documented by Cisco */
09793       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09794       add_header(req, "Content-Type", "application/dtmf-relay");
09795       add_header_contentLength(req, strlen(tmp));
09796       add_line(req, tmp);
09797    }
09798    return 0;
09799 }
09800 
09801 /*! \brief add XML encoded media control with update 
09802    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09803 static int add_vidupdate(struct sip_request *req)
09804 {
09805    const char *xml_is_a_huge_waste_of_space =
09806       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09807       " <media_control>\r\n"
09808       "  <vc_primitive>\r\n"
09809       "   <to_encoder>\r\n"
09810       "    <picture_fast_update>\r\n"
09811       "    </picture_fast_update>\r\n"
09812       "   </to_encoder>\r\n"
09813       "  </vc_primitive>\r\n"
09814       " </media_control>\r\n";
09815    add_header(req, "Content-Type", "application/media_control+xml");
09816    add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
09817    add_line(req, xml_is_a_huge_waste_of_space);
09818    return 0;
09819 }
09820 
09821 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09822 static void add_codec_to_sdp(const struct sip_pvt *p, int codec,
09823               struct ast_str **m_buf, struct ast_str **a_buf,
09824               int debug, int *min_packet_size)
09825 {
09826    int rtp_code;
09827    struct ast_format_list fmt;
09828 
09829 
09830    if (debug)
09831       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09832    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09833       return;
09834 
09835    if (p->rtp) {
09836       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09837       fmt = ast_codec_pref_getsize(pref, codec);
09838    } else /* I dont see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
09839       return;
09840    ast_str_append(m_buf, 0, " %d", rtp_code);
09841    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09842              ast_rtp_lookup_mime_subtype(1, codec,
09843                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09844              ast_rtp_lookup_sample_rate(1, codec));
09845 
09846    switch (codec) {
09847    case AST_FORMAT_G729A:
09848       /* Indicate that we don't support VAD (G.729 annex B) */
09849       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09850       break;
09851    case AST_FORMAT_G723_1:
09852       /* Indicate that we don't support VAD (G.723.1 annex A) */
09853       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09854       break;
09855    case AST_FORMAT_ILBC:
09856       /* Add information about us using only 20/30 ms packetization */
09857       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09858       break;
09859    case AST_FORMAT_SIREN7:
09860       /* Indicate that we only expect 32Kbps */
09861       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
09862       break;
09863    case AST_FORMAT_SIREN14:
09864       /* Indicate that we only expect 48Kbps */
09865       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
09866       break;
09867    }
09868 
09869    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09870       *min_packet_size = fmt.cur_ms;
09871 
09872    /* Our first codec packetization processed cannot be zero */
09873    if ((*min_packet_size)==0 && fmt.cur_ms)
09874       *min_packet_size = fmt.cur_ms;
09875 }
09876 
09877 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
09878 /* This is different to the audio one now so we can add more caps later */
09879 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec,
09880               struct ast_str **m_buf, struct ast_str **a_buf,
09881               int debug, int *min_packet_size)
09882 {
09883    int rtp_code;
09884 
09885    if (!p->vrtp)
09886       return;
09887 
09888    if (debug)
09889       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09890 
09891    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09892       return;
09893 
09894    ast_str_append(m_buf, 0, " %d", rtp_code);
09895    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09896              ast_rtp_lookup_mime_subtype(1, codec, 0),
09897              ast_rtp_lookup_sample_rate(1, codec));
09898    /* Add fmtp code here */
09899 }
09900 
09901 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
09902 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
09903               struct ast_str **m_buf, struct ast_str **a_buf,
09904               int debug, int *min_packet_size)
09905 {
09906    int rtp_code;
09907 
09908    if (!p->trtp)
09909       return;
09910 
09911    if (debug)
09912       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09913 
09914    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
09915       return;
09916 
09917    ast_str_append(m_buf, 0, " %d", rtp_code);
09918    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09919              ast_rtp_lookup_mime_subtype(1, codec, 0),
09920              ast_rtp_lookup_sample_rate(1, codec));
09921    /* Add fmtp code here */
09922 
09923    if (codec == AST_FORMAT_T140RED) {
09924       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
09925           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09926           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09927           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
09928 
09929    }
09930 }
09931 
09932 
09933 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
09934 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
09935 {
09936    switch (rate) {
09937    case AST_T38_RATE_2400:
09938       return 2400;
09939    case AST_T38_RATE_4800:
09940       return 4800;
09941    case AST_T38_RATE_7200:
09942       return 7200;
09943    case AST_T38_RATE_9600:
09944       return 9600;
09945    case AST_T38_RATE_12000:
09946       return 12000;
09947    case AST_T38_RATE_14400:
09948       return 14400;
09949    default:
09950       return 0;
09951    }
09952 }
09953 
09954 /*! \brief Add RFC 2833 DTMF offer to SDP */
09955 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
09956             struct ast_str **m_buf, struct ast_str **a_buf,
09957             int debug)
09958 {
09959    int rtp_code;
09960 
09961    if (debug)
09962       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
09963    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
09964       return;
09965 
09966    ast_str_append(m_buf, 0, " %d", rtp_code);
09967    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09968              ast_rtp_lookup_mime_subtype(0, format, 0),
09969              ast_rtp_lookup_sample_rate(0, format));
09970    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
09971       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
09972 }
09973 
09974 /*! \brief Set all IP media addresses for this call 
09975    \note called from add_sdp()
09976 */
09977 static void get_our_media_address(struct sip_pvt *p, int needvideo,
09978    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
09979    struct sockaddr_in *dest, struct sockaddr_in *vdest)
09980 {
09981    /* First, get our address */
09982    ast_rtp_get_us(p->rtp, sin);
09983    if (p->vrtp)
09984       ast_rtp_get_us(p->vrtp, vsin);
09985    if (p->trtp)
09986       ast_rtp_get_us(p->trtp, tsin);
09987 
09988    /* Now, try to figure out where we want them to send data */
09989    /* Is this a re-invite to move the media out, then use the original offer from caller  */
09990    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
09991       dest->sin_port = p->redirip.sin_port;
09992       dest->sin_addr = p->redirip.sin_addr;
09993    } else {
09994       dest->sin_addr = p->ourip.sin_addr;
09995       dest->sin_port = sin->sin_port;
09996    }
09997    if (needvideo) {
09998       /* Determine video destination */
09999       if (p->vredirip.sin_addr.s_addr) {
10000          vdest->sin_addr = p->vredirip.sin_addr;
10001          vdest->sin_port = p->vredirip.sin_port;
10002       } else {
10003          vdest->sin_addr = p->ourip.sin_addr;
10004          vdest->sin_port = vsin->sin_port;
10005       }
10006    }
10007 
10008 }
10009 
10010 /*! \brief Add Session Description Protocol message 
10011 
10012     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
10013     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
10014     without modifying the media session in any way. 
10015 */
10016 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
10017 {
10018    int len = 0;
10019    int alreadysent = 0;
10020 
10021    struct sockaddr_in sin;
10022    struct sockaddr_in vsin;
10023    struct sockaddr_in tsin;
10024    struct sockaddr_in dest;
10025    struct sockaddr_in udptlsin;
10026    struct sockaddr_in vdest = { 0, };
10027    struct sockaddr_in tdest = { 0, };
10028    struct sockaddr_in udptldest = { 0, };
10029 
10030    /* SDP fields */
10031    char *version =   "v=0\r\n";     /* Protocol version */
10032    char subject[256];            /* Subject of the session */
10033    char owner[256];           /* Session owner/creator */
10034    char connection[256];            /* Connection data */
10035    char *session_time = "t=0 0\r\n";         /* Time the session is active */
10036    char bandwidth[256] = "";        /* Max bitrate */
10037    char *hold = "";
10038    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
10039    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
10040    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
10041    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
10042    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
10043    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
10044    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
10045    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
10046 
10047    int x;
10048    int capability = 0;
10049    int needaudio = FALSE;
10050    int needvideo = FALSE;
10051    int needtext = FALSE;
10052    int debug = sip_debug_test_pvt(p);
10053    int min_audio_packet_size = 0;
10054    int min_video_packet_size = 0;
10055    int min_text_packet_size = 0;
10056 
10057    char codecbuf[SIPBUFSIZE];
10058    char buf[SIPBUFSIZE];
10059    char dummy_answer[256];
10060 
10061    /* Set the SDP session name */
10062    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
10063 
10064    if (!p->rtp) {
10065       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
10066       return AST_FAILURE;
10067    }
10068    /* XXX We should not change properties in the SIP dialog until 
10069       we have acceptance of the offer if this is a re-invite */
10070 
10071    /* Set RTP Session ID and version */
10072    if (!p->sessionid) {
10073       p->sessionid = (int)ast_random();
10074       p->sessionversion = p->sessionid;
10075    } else {
10076       if (oldsdp == FALSE)
10077          p->sessionversion++;
10078    }
10079 
10080    if (add_audio) {
10081       /* Check if we need video in this call */
10082       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
10083          if (p->vrtp) {
10084             needvideo = TRUE;
10085             ast_debug(2, "This call needs video offers!\n");
10086          } else
10087             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
10088       }
10089       /* Check if we need text in this call */
10090       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
10091          if (sipdebug_text)
10092             ast_verbose("We think we can do text\n");
10093          if (p->trtp) {
10094             if (sipdebug_text) {
10095                ast_verbose("And we have a text rtp object\n");
10096             }
10097             needtext = TRUE;
10098             ast_debug(2, "This call needs text offers! \n");
10099          } else {
10100             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
10101          }
10102       }
10103    }
10104 
10105    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
10106 
10107    snprintf(owner, sizeof(owner), "o=%s %d %d IN IP4 %s\r\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner, p->sessionid, p->sessionversion, ast_inet_ntoa(dest.sin_addr));
10108    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
10109 
10110    if (add_audio) {
10111       capability = p->jointcapability;
10112 
10113       /* XXX note, Video and Text are negated - 'true' means 'no' */
10114       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
10115            p->novideo ? "True" : "False", p->notext ? "True" : "False");
10116       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
10117 
10118       /* Check if we need audio */
10119       if (capability & AST_FORMAT_AUDIO_MASK)
10120          needaudio = TRUE;
10121 
10122       if (debug) 
10123          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
10124 
10125       /* Ok, we need video. Let's add what we need for video and set codecs.
10126          Video is handled differently than audio since we can not transcode. */
10127       if (needvideo) {
10128          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
10129 
10130          /* Build max bitrate string */
10131          if (p->maxcallbitrate)
10132             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
10133          if (debug) 
10134             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
10135       }
10136 
10137       /* Ok, we need text. Let's add what we need for text and set codecs.
10138          Text is handled differently than audio since we can not transcode. */
10139       if (needtext) {
10140          if (sipdebug_text)
10141             ast_verbose("Lets set up the text sdp\n");
10142          /* Determine text destination */
10143          if (p->tredirip.sin_addr.s_addr) {
10144             tdest.sin_addr = p->tredirip.sin_addr;
10145             tdest.sin_port = p->tredirip.sin_port;
10146          } else {
10147             tdest.sin_addr = p->ourip.sin_addr;
10148             tdest.sin_port = tsin.sin_port;
10149          }
10150          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
10151          if (debug) /* XXX should I use tdest below ? */
10152             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
10153 
10154       }
10155 
10156       /* Start building generic SDP headers */
10157 
10158       /* We break with the "recommendation" and send our IP, in order that our
10159          peer doesn't have to ast_gethostbyname() us */
10160 
10161       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
10162 
10163       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
10164          hold = "a=recvonly\r\n";
10165       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
10166          hold = "a=inactive\r\n";
10167       else
10168          hold = "a=sendrecv\r\n";
10169 
10170       /* Now, start adding audio codecs. These are added in this order:
10171          - First what was requested by the calling channel
10172          - Then preferences in order from sip.conf device config for this peer/user
10173          - Then other codecs in capabilities, including video
10174       */
10175 
10176       /* Prefer the audio codec we were requested to use, first, no matter what 
10177          Note that p->prefcodec can include video codecs, so mask them out
10178       */
10179       if (capability & p->prefcodec) {
10180          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
10181 
10182          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10183          alreadysent |= codec;
10184       }
10185 
10186       /* Start by sending our preferred audio/video codecs */
10187       for (x = 0; x < 32; x++) {
10188          int codec;
10189 
10190          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
10191             break; 
10192 
10193          if (!(capability & codec))
10194             continue;
10195 
10196          if (alreadysent & codec)
10197             continue;
10198 
10199          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
10200          alreadysent |= codec;
10201       }
10202 
10203       /* Now send any other common audio and video codecs, and non-codec formats: */
10204       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
10205          if (!(capability & x))  /* Codec not requested */
10206             continue;
10207 
10208          if (alreadysent & x) /* Already added to SDP */
10209             continue;
10210 
10211          if (x & AST_FORMAT_AUDIO_MASK)
10212             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
10213          else if (x & AST_FORMAT_VIDEO_MASK)
10214             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
10215          else if (x & AST_FORMAT_TEXT_MASK)
10216             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
10217       }
10218 
10219       /* Now add DTMF RFC2833 telephony-event as a codec */
10220       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
10221          if (!(p->jointnoncodeccapability & x))
10222             continue;
10223 
10224          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
10225       }
10226 
10227       ast_debug(3, "-- Done with adding codecs to SDP\n");
10228 
10229       if (!p->owner || !ast_internal_timing_enabled(p->owner))
10230          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
10231 
10232       if (min_audio_packet_size)
10233          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
10234 
10235       /* XXX don't think you can have ptime for video */
10236       if (min_video_packet_size)
10237          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
10238 
10239       /* XXX don't think you can have ptime for text */
10240       if (min_text_packet_size)
10241          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
10242  
10243       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
10244           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
10245           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
10246          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
10247    }
10248 
10249    if (add_t38) {
10250       /* Our T.38 end is */
10251       ast_udptl_get_us(p->udptl, &udptlsin);
10252 
10253       /* Determine T.38 UDPTL destination */
10254       if (p->udptlredirip.sin_addr.s_addr) {
10255          udptldest.sin_port = p->udptlredirip.sin_port;
10256          udptldest.sin_addr = p->udptlredirip.sin_addr;
10257       } else {
10258          udptldest.sin_addr = p->ourip.sin_addr;
10259          udptldest.sin_port = udptlsin.sin_port;
10260       }
10261 
10262       if (debug)
10263          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
10264 
10265       /* We break with the "recommendation" and send our IP, in order that our
10266          peer doesn't have to ast_gethostbyname() us */
10267 
10268       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
10269 
10270       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
10271       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
10272       if (p->t38.our_parms.fill_bit_removal) {
10273          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
10274       }
10275       if (p->t38.our_parms.transcoding_mmr) {
10276          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
10277       }
10278       if (p->t38.our_parms.transcoding_jbig) {
10279          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
10280       }
10281       switch (p->t38.our_parms.rate_management) {
10282       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
10283          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
10284          break;
10285       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
10286          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
10287          break;
10288       }
10289       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
10290       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
10291       case UDPTL_ERROR_CORRECTION_NONE:
10292          break;
10293       case UDPTL_ERROR_CORRECTION_FEC:
10294          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
10295          break;
10296       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
10297          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
10298          break;
10299       }
10300    }
10301 
10302    if (needaudio)
10303       ast_str_append(&m_audio, 0, "\r\n");
10304    if (needvideo)
10305       ast_str_append(&m_video, 0, "\r\n");
10306    if (needtext)
10307       ast_str_append(&m_text, 0, "\r\n");
10308 
10309    len = strlen(version) + strlen(subject) + strlen(owner) +
10310       strlen(connection) + strlen(session_time);
10311    if (needaudio)
10312       len += m_audio->used + a_audio->used + strlen(hold);
10313    if (needvideo) /* only if video response is appropriate */
10314       len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
10315    if (needtext) /* only if text response is appropriate */
10316       len += m_text->used + a_text->used + strlen(hold);
10317    if (add_t38)
10318       len += m_modem->used + a_modem->used;
10319 
10320    add_header(resp, "Content-Type", "application/sdp");
10321    add_header_contentLength(resp, len);
10322    add_line(resp, version);
10323    add_line(resp, owner);
10324    add_line(resp, subject);
10325    add_line(resp, connection);
10326    if (needvideo)    /* only if video response is appropriate */
10327       add_line(resp, bandwidth);
10328    add_line(resp, session_time);
10329    if (needaudio) {
10330       add_line(resp, m_audio->str);
10331       add_line(resp, a_audio->str);
10332       add_line(resp, hold);
10333    } else if (p->offered_media[SDP_AUDIO].offered) {
10334       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
10335       add_line(resp, dummy_answer);
10336    }
10337    if (needvideo) { /* only if video response is appropriate */
10338       add_line(resp, m_video->str);
10339       add_line(resp, a_video->str);
10340       add_line(resp, hold);   /* Repeat hold for the video stream */
10341    } else if (p->offered_media[SDP_VIDEO].offered) {
10342       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
10343       add_line(resp, dummy_answer);
10344    }
10345    if (needtext) { /* only if text response is appropriate */
10346       add_line(resp, m_text->str);
10347       add_line(resp, a_text->str);
10348       add_line(resp, hold);   /* Repeat hold for the text stream */
10349    } else if (p->offered_media[SDP_TEXT].offered) {
10350       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
10351       add_line(resp, dummy_answer);
10352    }
10353    if (add_t38) {
10354       add_line(resp, m_modem->str);
10355       add_line(resp, a_modem->str);
10356    } else if (p->offered_media[SDP_IMAGE].offered) {
10357       add_line(resp, "m=image 0 udptl t38\r\n");
10358    }
10359 
10360    /* Update lastrtprx when we send our SDP */
10361    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
10362 
10363    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
10364 
10365    return AST_SUCCESS;
10366 }
10367 
10368 /*! \brief Used for 200 OK and 183 early media */
10369 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
10370 {
10371    struct sip_request resp;
10372    int seqno;
10373    
10374    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10375       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10376       return -1;
10377    }
10378    respprep(&resp, p, msg, req);
10379    if (p->udptl) {
10380       add_sdp(&resp, p, 0, 0, 1);
10381    } else 
10382       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
10383    if (retrans && !p->pendinginvite)
10384       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10385    return send_response(p, &resp, retrans, seqno);
10386 }
10387 
10388 /*! \brief copy SIP request (mostly used to save request for responses) */
10389 static void copy_request(struct sip_request *dst, const struct sip_request *src)
10390 {
10391    struct ast_str *duplicate = dst->data;
10392 
10393    /* First copy stuff */
10394    memcpy(dst, src, sizeof(*dst));
10395    dst->data = duplicate;
10396 
10397    /* All these + 1's are to account for the need to include the NULL terminator
10398     * Using typical string functions like ast_copy_string or ast_str_set will not
10399     * work in this case because the src's data string is riddled with \0's all over
10400     * the place and so a memcpy is the only way to accurately copy the string
10401     */
10402 
10403    if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
10404       return;
10405    else if (dst->data->len < src->data->used + 1)
10406       ast_str_make_space(&dst->data, src->data->used + 1);
10407       
10408    memcpy(dst->data->str, src->data->str, src->data->used + 1);
10409    dst->data->used = src->data->used;
10410 }
10411 
10412 /*! \brief Used for 200 OK and 183 early media 
10413    \return Will return XMIT_ERROR for network errors.
10414 */
10415 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
10416 {
10417    struct sip_request resp;
10418    int seqno;
10419    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
10420       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
10421       return -1;
10422    }
10423    respprep(&resp, p, msg, req);
10424    if (p->rtp) {
10425       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
10426          ast_debug(1, "Setting framing from config on incoming call\n");
10427          ast_rtp_codec_setpref(p->rtp, &p->prefs);
10428       }
10429       try_suggested_sip_codec(p);
10430       if (p->t38.state == T38_ENABLED) {
10431          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
10432       } else {
10433          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
10434       }
10435    } else 
10436       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
10437    if (reliable && !p->pendinginvite)
10438       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
10439    return send_response(p, &resp, reliable, seqno);
10440 }
10441 
10442 /*! \brief Parse first line of incoming SIP request */
10443 static int determine_firstline_parts(struct sip_request *req) 
10444 {
10445    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
10446    char *local_rlPart1;
10447 
10448    if (!*e)
10449       return -1;
10450    req->rlPart1 = e - req->data->str;  /* method or protocol */
10451    local_rlPart1 = e;
10452    e = ast_skip_nonblanks(e);
10453    if (*e)
10454       *e++ = '\0';
10455    /* Get URI or status code */
10456    e = ast_skip_blanks(e);
10457    if ( !*e )
10458       return -1;
10459    ast_trim_blanks(e);
10460 
10461    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
10462       if (strlen(e) < 3)   /* status code is 3 digits */
10463          return -1;
10464       req->rlPart2 = e - req->data->str;
10465    } else { /* We have a request */
10466       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
10467          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
10468          e++;
10469          if (!*e)
10470             return -1; 
10471       }
10472       req->rlPart2 = e - req->data->str;  /* URI */
10473       e = ast_skip_nonblanks(e);
10474       if (*e)
10475          *e++ = '\0';
10476       e = ast_skip_blanks(e);
10477       if (strcasecmp(e, "SIP/2.0") ) {
10478          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
10479          return -1;
10480       }
10481    }
10482    return 1;
10483 }
10484 
10485 /*! \brief Transmit reinvite with SDP
10486 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
10487    INVITE that opened the SIP dialogue 
10488    We reinvite so that the audio stream (RTP) go directly between
10489    the SIP UAs. SIP Signalling stays with * in the path.
10490    
10491    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
10492    T38 UDPTL transmission on the channel
10493 
10494     If oldsdp is TRUE then the SDP version number is not incremented. This
10495     is needed for Session-Timers so we can send a re-invite to refresh the
10496     SIP session without modifying the media session. 
10497 */
10498 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
10499 {
10500    struct sip_request req;
10501    
10502    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
10503 
10504    add_header(&req, "Allow", ALLOWED_METHODS);
10505    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10506    if (sipdebug) {
10507       if (oldsdp == TRUE)
10508          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
10509       else
10510          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
10511    }
10512 
10513    if (p->do_history)
10514       append_history(p, "ReInv", "Re-invite sent");
10515    memset(p->offered_media, 0, sizeof(p->offered_media));
10516 
10517    if (t38version)
10518       add_sdp(&req, p, oldsdp, FALSE, TRUE);
10519    else
10520       add_sdp(&req, p, oldsdp, TRUE, FALSE);
10521 
10522    /* Use this as the basis */
10523    initialize_initreq(p, &req);
10524    p->lastinvite = p->ocseq;
10525    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
10526 
10527    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
10528 }
10529 
10530 /* \brief Remove URI parameters at end of URI, not in username part though */
10531 static char *remove_uri_parameters(char *uri)
10532 {
10533    char *atsign;
10534    atsign = strchr(uri, '@'); /* First, locate the at sign */
10535    if (!atsign)
10536       atsign = uri;  /* Ok hostname only, let's stick with the rest */
10537    atsign = strchr(atsign, ';'); /* Locate semi colon */
10538    if (atsign)
10539       *atsign = '\0';   /* Kill at the semi colon */
10540    return uri;
10541 }
10542 
10543 /*! \brief Check Contact: URI of SIP message */
10544 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
10545 {
10546    char stripped[SIPBUFSIZE];
10547    char *c;
10548 
10549    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
10550    c = get_in_brackets(stripped);
10551    /* Cut the URI at the at sign after the @, not in the username part */
10552    c = remove_uri_parameters(c);
10553    if (!ast_strlen_zero(c))
10554       ast_string_field_set(p, uri, c);
10555 
10556 }
10557 
10558 /*! \brief Build contact header - the contact header we send out */
10559 static void build_contact(struct sip_pvt *p)
10560 {
10561 
10562    int ourport = ntohs(p->ourip.sin_port);
10563    /* only add port if it's non-standard for the transport type */
10564    if (!sip_standard_port(p->socket.type, ourport)) {
10565       if (p->socket.type == SIP_TRANSPORT_UDP)
10566          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport);
10567       else
10568          ast_string_field_build(p, our_contact, "<sip:%s%s%s:%d;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
10569    } else {
10570       if (p->socket.type == SIP_TRANSPORT_UDP)
10571          ast_string_field_build(p, our_contact, "<sip:%s%s%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr));
10572       else
10573          ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", p->exten, ast_strlen_zero(p->exten) ? "" : "@", ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
10574    }
10575 }
10576 
10577 /*! \brief Build the Remote Party-ID & From using callingpres options */
10578 static void build_rpid(struct sip_pvt *p)
10579 {
10580    int send_pres_tags = TRUE;
10581    const char *privacy=NULL;
10582    const char *screen=NULL;
10583    char buf[256];
10584    const char *clid = default_callerid;
10585    const char *clin = NULL;
10586    const char *fromdomain;
10587 
10588    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
10589       return;
10590 
10591    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
10592       clid = p->owner->cid.cid_num;
10593    if (p->owner && p->owner->cid.cid_name)
10594       clin = p->owner->cid.cid_name;
10595    if (ast_strlen_zero(clin))
10596       clin = clid;
10597 
10598    switch (p->callingpres) {
10599    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
10600       privacy = "off";
10601       screen = "no";
10602       break;
10603    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
10604       privacy = "off";
10605       screen = "yes";
10606       break;
10607    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
10608       privacy = "off";
10609       screen = "no";
10610       break;
10611    case AST_PRES_ALLOWED_NETWORK_NUMBER:
10612       privacy = "off";
10613       screen = "yes";
10614       break;
10615    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
10616       privacy = "full";
10617       screen = "no";
10618       break;
10619    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
10620       privacy = "full";
10621       screen = "yes";
10622       break;
10623    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
10624       privacy = "full";
10625       screen = "no";
10626       break;
10627    case AST_PRES_PROHIB_NETWORK_NUMBER:
10628       privacy = "full";
10629       screen = "yes";
10630       break;
10631    case AST_PRES_NUMBER_NOT_AVAILABLE:
10632       send_pres_tags = FALSE;
10633       break;
10634    default:
10635       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10636       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10637          privacy = "full";
10638       else
10639          privacy = "off";
10640       screen = "no";
10641       break;
10642    }
10643    
10644    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10645 
10646    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10647    if (send_pres_tags)
10648       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10649    ast_string_field_set(p, rpid, buf);
10650 
10651    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10652                 S_OR(p->fromuser, clid),
10653                 fromdomain, p->tag);
10654 }
10655 
10656 /*! \brief Initiate new SIP request to peer/user */
10657 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10658 {
10659    struct ast_str *invite = ast_str_alloca(256);
10660    char from[256];
10661    char to[256];
10662    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10663    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10664    const char *l = NULL;   /* XXX what is this, exactly ? */
10665    const char *n = NULL;   /* XXX what is this, exactly ? */
10666    const char *d = NULL;   /* domain in from header */
10667    const char *urioptions = "";
10668    int ourport;
10669 
10670    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10671       const char *s = p->username;  /* being a string field, cannot be NULL */
10672 
10673       /* Test p->username against allowed characters in AST_DIGIT_ANY
10674          If it matches the allowed characters list, then sipuser = ";user=phone"
10675          If not, then sipuser = ""
10676       */
10677       /* + is allowed in first position in a tel: uri */
10678       if (*s == '+')
10679          s++;
10680       for (; *s; s++) {
10681          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10682             break;
10683       }
10684       /* If we have only digits, add ;user=phone to the uri */
10685       if (!*s)
10686          urioptions = ";user=phone";
10687    }
10688 
10689 
10690    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10691 
10692    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10693    if (p->owner) {
10694       l = p->owner->cid.cid_num;
10695       n = p->owner->cid.cid_name;
10696    }
10697    /* if we are not sending RPID and user wants his callerid restricted */
10698    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10699        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10700       l = CALLERID_UNKNOWN;
10701       n = l;
10702       d = FROMDOMAIN_INVALID;
10703    }
10704    if (ast_strlen_zero(l))
10705       l = default_callerid;
10706    if (ast_strlen_zero(n))
10707       n = l;
10708    /* Allow user to be overridden */
10709    if (!ast_strlen_zero(p->fromuser))
10710       l = p->fromuser;
10711    else /* Save for any further attempts */
10712       ast_string_field_set(p, fromuser, l);
10713 
10714    /* Allow user to be overridden */
10715    if (!ast_strlen_zero(p->fromname))
10716       n = p->fromname;
10717    else /* Save for any further attempts */
10718       ast_string_field_set(p, fromname, n);
10719 
10720    if (sip_cfg.pedanticsipchecking) {
10721       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10722       n = tmp_n;
10723       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10724       l = tmp_l;
10725    }
10726 
10727    ourport = ntohs(p->ourip.sin_port);
10728    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10729       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10730    else
10731       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10732 
10733    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10734    if (!ast_strlen_zero(p->fullcontact)) {
10735       /* If we have full contact, trust it */
10736       ast_str_append(&invite, 0, "%s", p->fullcontact);
10737    } else {
10738       /* Otherwise, use the username while waiting for registration */
10739       ast_str_append(&invite, 0, "sip:");
10740       if (!ast_strlen_zero(p->username)) {
10741          n = p->username;
10742          if (sip_cfg.pedanticsipchecking) {
10743             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10744             n = tmp_n;
10745          }
10746          ast_str_append(&invite, 0, "%s@", n);
10747       }
10748       ast_str_append(&invite, 0, "%s", p->tohost);
10749       if (p->portinuri)
10750          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10751       ast_str_append(&invite, 0, "%s", urioptions);
10752    }
10753 
10754    /* If custom URI options have been provided, append them */
10755    if (p->options && !ast_strlen_zero(p->options->uri_options))
10756       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10757    
10758    /* This is the request URI, which is the next hop of the call
10759       which may or may not be the destination of the call
10760    */
10761    ast_string_field_set(p, uri, invite->str);
10762   
10763    if (!ast_strlen_zero(p->todnid)) {
10764       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10765       if (!strchr(p->todnid, '@')) {
10766          /* We have no domain in the dnid */
10767          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10768       } else {
10769          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10770       }
10771    } else {
10772       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10773          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10774          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10775       } else if (p->options && p->options->vxml_url) {
10776          /* If there is a VXML URL append it to the SIP URL */
10777          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10778       } else 
10779          snprintf(to, sizeof(to), "<%s>", p->uri);
10780    }
10781 
10782    init_req(req, sipmethod, p->uri);
10783    /* now tmp_n is available so reuse it to build the CSeq */
10784    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10785 
10786    add_header(req, "Via", p->via);
10787    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10788    /* This will be a no-op most of the time. However, under certain circumstances,
10789     * NOTIFY messages will use this function for preparing the request and should
10790     * have Route headers present.
10791     */
10792    add_route(req, p->route);
10793 
10794    /* Build Remote Party-ID and From */
10795    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10796       build_rpid(p);
10797       add_header(req, "From", p->rpid_from);
10798    } else 
10799       add_header(req, "From", from);
10800    add_header(req, "To", to);
10801    ast_string_field_set(p, exten, l);
10802    build_contact(p);
10803    add_header(req, "Contact", p->our_contact);
10804    add_header(req, "Call-ID", p->callid);
10805    add_header(req, "CSeq", tmp_n);
10806    if (!ast_strlen_zero(global_useragent))
10807       add_header(req, "User-Agent", global_useragent);
10808    if (!ast_strlen_zero(p->rpid))
10809       add_header(req, "Remote-Party-ID", p->rpid);
10810 }
10811 
10812 /*! \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it 
10813    \param init 0 = Prepare request within dialog, 1= prepare request, new branch, 2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
10814  \param p sip_pvt structure
10815  \param sdp unknown 
10816  \param sipmethod unknown 
10817  
10818 */
10819 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10820 {
10821    struct sip_request req;
10822    struct ast_variable *var;
10823    
10824    req.method = sipmethod;
10825    if (init) {/* Bump branch even on initial requests */
10826       p->branch ^= ast_random();
10827       p->invite_branch = p->branch;
10828       build_via(p);
10829    }
10830    if (init > 1)
10831       initreqprep(&req, p, sipmethod);
10832    else
10833       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
10834       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10835       
10836    if (p->options && p->options->auth)
10837       add_header(&req, p->options->authheader, p->options->auth);
10838    append_date(&req);
10839    if (sipmethod == SIP_REFER) { /* Call transfer */
10840       if (p->refer) {
10841          char buf[SIPBUFSIZE];
10842          if (!ast_strlen_zero(p->refer->refer_to))
10843             add_header(&req, "Refer-To", p->refer->refer_to);
10844          if (!ast_strlen_zero(p->refer->referred_by)) {
10845             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10846             add_header(&req, "Referred-By", buf);
10847          }
10848       }
10849    } else if (sipmethod == SIP_SUBSCRIBE) { /* We only support sending MWI subscriptions right now */
10850       char buf[SIPBUFSIZE];
10851 
10852       add_header(&req, "Event", "message-summary");
10853       add_header(&req, "Accept", "application/simple-message-summary");
10854       snprintf(buf, sizeof(buf), "%d", mwi_expiry);
10855       add_header(&req, "Expires", buf);
10856    }
10857 
10858    /* This new INVITE is part of an attended transfer. Make sure that the
10859    other end knows and replace the current call with this new call */
10860    if (p->options && !ast_strlen_zero(p->options->replaces)) {
10861       add_header(&req, "Replaces", p->options->replaces);
10862       add_header(&req, "Require", "replaces");
10863    }
10864 
10865    /* Add Session-Timers related headers */
10866    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10867       char i2astr[10];
10868 
10869       if (!p->stimer->st_interval)
10870          p->stimer->st_interval = st_get_se(p, TRUE);
10871 
10872       p->stimer->st_active = TRUE;
10873       
10874       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10875       add_header(&req, "Session-Expires", i2astr);
10876       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10877       add_header(&req, "Min-SE", i2astr);
10878    }
10879 
10880    add_header(&req, "Allow", ALLOWED_METHODS);
10881    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10882 
10883    if(p->notify_headers) {
10884       char buf[512];
10885       for (var = p->notify_headers; var; var = var->next) {
10886          ast_copy_string(buf, var->value, sizeof(buf));
10887          add_header(&req, var->name, ast_unescape_semicolon(buf));
10888       }
10889    }
10890    if (p->options && p->options->addsipheaders && p->owner) {
10891       struct ast_channel *chan = p->owner; /* The owner channel */
10892       struct varshead *headp;
10893    
10894       ast_channel_lock(chan);
10895 
10896       headp = &chan->varshead;
10897 
10898       if (!headp)
10899          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10900       else {
10901          const struct ast_var_t *current;
10902          AST_LIST_TRAVERSE(headp, current, entries) {  
10903             /* SIPADDHEADER: Add SIP header to outgoing call */
10904             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10905                char *content, *end;
10906                const char *header = ast_var_value(current);
10907                char *headdup = ast_strdupa(header);
10908 
10909                /* Strip of the starting " (if it's there) */
10910                if (*headdup == '"')
10911                   headdup++;
10912                if ((content = strchr(headdup, ':'))) {
10913                   *content++ = '\0';
10914                   content = ast_skip_blanks(content); /* Skip white space */
10915                   /* Strip the ending " (if it's there) */
10916                   end = content + strlen(content) -1; 
10917                   if (*end == '"')
10918                      *end = '\0';
10919                
10920                   add_header(&req, headdup, content);
10921                   if (sipdebug)
10922                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
10923                }
10924             }
10925          }
10926       }
10927 
10928       ast_channel_unlock(chan);
10929    }
10930    if (sdp) {
10931       memset(p->offered_media, 0, sizeof(p->offered_media));
10932       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
10933          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
10934          add_sdp(&req, p, FALSE, FALSE, TRUE);
10935       } else if (p->rtp) 
10936          add_sdp(&req, p, FALSE, TRUE, FALSE);
10937    } else {
10938       if (!p->notify_headers) {
10939          add_header_contentLength(&req, 0);
10940       }
10941    }
10942 
10943    if (!p->initreq.headers || init > 2)
10944       initialize_initreq(p, &req);
10945    p->lastinvite = p->ocseq;
10946    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
10947 }
10948 
10949 /*! \brief Send a subscription or resubscription for MWI */
10950 static int sip_subscribe_mwi_do(const void *data)
10951 {
10952    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
10953    
10954    if (!mwi) {
10955       return -1;
10956    }
10957    
10958    mwi->resub = -1;
10959    __sip_subscribe_mwi_do(mwi);
10960    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
10961    
10962    return 0;
10963 }
10964 
10965 /*! \brief Actually setup an MWI subscription or resubscribe */
10966 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
10967 {
10968    /* If we have no DNS manager let's do a lookup */
10969    if (!mwi->dnsmgr) {
10970       char transport[MAXHOSTNAMELEN];
10971       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(mwi->transport));
10972       ast_dnsmgr_lookup(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
10973    }
10974 
10975    /* If we already have a subscription up simply send a resubscription */
10976    if (mwi->call) {
10977       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0);
10978       return 0;
10979    }
10980    
10981    /* Create a dialog that we will use for the subscription */
10982    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
10983       return -1;
10984    }
10985 
10986    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
10987 
10988    if (!mwi->us.sin_port && mwi->portno) {
10989       mwi->us.sin_port = htons(mwi->portno);
10990    }
10991    
10992    /* Setup the destination of our subscription */
10993    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
10994       dialog_unlink_all(mwi->call, TRUE, TRUE);
10995       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
10996       return 0;
10997    }
10998    
10999    if (!mwi->dnsmgr && mwi->portno) {
11000       mwi->call->sa.sin_port = htons(mwi->portno);
11001       mwi->call->recv.sin_port = htons(mwi->portno);
11002    } else {
11003       mwi->portno = ntohs(mwi->call->sa.sin_port);
11004    }
11005    
11006    /* Set various other information */
11007    if (!ast_strlen_zero(mwi->authuser)) {
11008       ast_string_field_set(mwi->call, peername, mwi->authuser);
11009       ast_string_field_set(mwi->call, authname, mwi->authuser);
11010       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
11011    } else {
11012       ast_string_field_set(mwi->call, peername, mwi->username);
11013       ast_string_field_set(mwi->call, authname, mwi->username);
11014       ast_string_field_set(mwi->call, fromuser, mwi->username);
11015    }
11016    ast_string_field_set(mwi->call, username, mwi->username);
11017    if (!ast_strlen_zero(mwi->secret)) {
11018       ast_string_field_set(mwi->call, peersecret, mwi->secret);
11019    }
11020    set_socket_transport(&mwi->call->socket, mwi->transport);
11021    mwi->call->socket.port = htons(mwi->portno);
11022    ast_sip_ouraddrfor(&mwi->call->sa.sin_addr, &mwi->call->ourip, mwi->call);
11023    build_contact(mwi->call);
11024    build_via(mwi->call);
11025    build_callid_pvt(mwi->call);
11026    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
11027    
11028    /* Associate the call with us */
11029    mwi->call->mwi = ASTOBJ_REF(mwi);
11030    
11031    /* Actually send the packet */
11032    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2);
11033 
11034    return 0;
11035 }
11036 
11037 static int find_calling_channel(struct ast_channel *c, void *data) {
11038    struct sip_pvt *p = data;
11039 
11040    return (c->pbx &&
11041          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
11042          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
11043 }
11044 
11045 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
11046 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
11047 {
11048    struct ast_str *tmp = ast_str_alloca(4000);
11049    char from[256], to[256];
11050    char *c, *mfrom, *mto;
11051    struct sip_request req;
11052    char hint[AST_MAX_EXTENSION];
11053    char *statestring = "terminated";
11054    const struct cfsubscription_types *subscriptiontype;
11055    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
11056    char *pidfstate = "--";
11057    char *pidfnote= "Ready";
11058    
11059    memset(from, 0, sizeof(from));
11060    memset(to, 0, sizeof(to));
11061 
11062    switch (state) {
11063    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
11064       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
11065       local_state = NOTIFY_INUSE;
11066       pidfstate = "busy";
11067       pidfnote = "Ringing";
11068       break;
11069    case AST_EXTENSION_RINGING:
11070       statestring = "early";
11071       local_state = NOTIFY_INUSE;
11072       pidfstate = "busy";
11073       pidfnote = "Ringing";
11074       break;
11075    case AST_EXTENSION_INUSE:
11076       statestring = "confirmed";
11077       local_state = NOTIFY_INUSE;
11078       pidfstate = "busy";
11079       pidfnote = "On the phone";
11080       break;
11081    case AST_EXTENSION_BUSY:
11082       statestring = "confirmed";
11083       local_state = NOTIFY_CLOSED;
11084       pidfstate = "busy";
11085       pidfnote = "On the phone";
11086       break;
11087    case AST_EXTENSION_UNAVAILABLE:
11088       statestring = "terminated";
11089       local_state = NOTIFY_CLOSED;
11090       pidfstate = "away";
11091       pidfnote = "Unavailable";
11092       break;
11093    case AST_EXTENSION_ONHOLD:
11094       statestring = "confirmed";
11095       local_state = NOTIFY_CLOSED;
11096       pidfstate = "busy";
11097       pidfnote = "On hold";
11098       break;
11099    case AST_EXTENSION_NOT_INUSE:
11100    default:
11101       /* Default setting */
11102       break;
11103    }
11104 
11105    subscriptiontype = find_subscription_type(p->subscribed);
11106    
11107    /* Check which device/devices we are watching  and if they are registered */
11108    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
11109       char *hint2 = hint, *individual_hint = NULL;
11110       int hint_count = 0, unavailable_count = 0;
11111 
11112       while ((individual_hint = strsep(&hint2, "&"))) {
11113          hint_count++;
11114 
11115          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
11116             unavailable_count++;
11117       }
11118 
11119       /* If none of the hinted devices are registered, we will
11120        * override notification and show no availability.
11121        */
11122       if (hint_count > 0 && hint_count == unavailable_count) {
11123          local_state = NOTIFY_CLOSED;
11124          pidfstate = "away";
11125          pidfnote = "Not online";
11126       }
11127    }
11128 
11129    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
11130    c = get_in_brackets(from);
11131    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11132       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11133       return -1;
11134    }
11135    
11136    mfrom = remove_uri_parameters(c);
11137 
11138    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
11139    c = get_in_brackets(to);
11140    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
11141       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
11142       return -1;
11143    }
11144    mto = remove_uri_parameters(c);
11145 
11146    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11147 
11148    
11149    add_header(&req, "Event", subscriptiontype->event);
11150    add_header(&req, "Content-Type", subscriptiontype->mediatype);
11151    switch(state) {
11152    case AST_EXTENSION_DEACTIVATED:
11153       if (timeout)
11154          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11155       else {
11156          add_header(&req, "Subscription-State", "terminated;reason=probation");
11157          add_header(&req, "Retry-After", "60");
11158       }
11159       break;
11160    case AST_EXTENSION_REMOVED:
11161       add_header(&req, "Subscription-State", "terminated;reason=noresource");
11162       break;
11163    default:
11164       if (p->expiry)
11165          add_header(&req, "Subscription-State", "active");
11166       else  /* Expired */
11167          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11168    }
11169    switch (p->subscribed) {
11170    case XPIDF_XML:
11171    case CPIM_PIDF_XML:
11172       ast_str_append(&tmp, 0,
11173          "<?xml version=\"1.0\"?>\n"
11174          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
11175          "<presence>\n");
11176       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
11177       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
11178       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
11179       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
11180       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
11181       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
11182       break;
11183    case PIDF_XML: /* Eyebeam supports this format */
11184       ast_str_append(&tmp, 0,
11185          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
11186          "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
11187       ast_str_append(&tmp, 0, "<pp:person><status>\n");
11188       if (pidfstate[0] != '-')
11189          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
11190       ast_str_append(&tmp, 0, "</status></pp:person>\n");
11191       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
11192       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
11193       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
11194       if (pidfstate[0] == 'b') /* Busy? Still open ... */
11195          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
11196       else
11197          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
11198       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
11199       break;
11200    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
11201       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
11202       ast_str_append(&tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full" : "partial", mto);
11203       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
11204          const char *local_display = p->exten;
11205          char *local_target = mto;
11206 
11207          /* There are some limitations to how this works.  The primary one is that the
11208             callee must be dialing the same extension that is being monitored.  Simply dialing
11209             the hint'd device is not sufficient. */
11210          if (sip_cfg.notifycid) {
11211             struct ast_channel *caller = ast_channel_search_locked(find_calling_channel, p);
11212 
11213             if (caller) {
11214                int need = strlen(caller->cid.cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
11215                local_target = alloca(need);
11216                snprintf(local_target, need, "sip:%s@%s", caller->cid.cid_num, p->fromdomain);
11217                local_display = ast_strdupa(caller->cid.cid_name);
11218                ast_channel_unlock(caller);
11219                caller = NULL;
11220             }
11221          }
11222 
11223          /* We create a fake call-id which the phone will send back in an INVITE
11224             Replaces header which we can grab and do some magic with. */
11225          ast_str_append(&tmp, 0, 
11226                "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n"
11227                "<remote>\n"
11228                /* See the limitations of this above.  Luckily the phone seems to still be
11229                   happy when these values are not correct. */
11230                "<identity display=\"%s\">%s</identity>\n"
11231                "<target uri=\"%s\"/>\n"
11232                "</remote>\n"
11233                "<local>\n"
11234                "<identity>%s</identity>\n"
11235                "<target uri=\"%s\"/>\n"
11236                "</local>\n",
11237                p->exten, p->callid, local_display, local_target, local_target, mto, mto);
11238       } else {
11239          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
11240       }
11241       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
11242       if (state == AST_EXTENSION_ONHOLD) {
11243          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
11244                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
11245                                          "</target>\n</local>\n", mto);
11246       }
11247       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
11248       break;
11249    case NONE:
11250    default:
11251       break;
11252    }
11253 
11254    add_header_contentLength(&req, tmp->used);
11255    add_line(&req, tmp->str);
11256 
11257    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
11258 
11259    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11260 }
11261 
11262 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
11263 \note - Notification only works for registered peers with mailbox= definitions
11264    in sip.conf
11265    - We use the SIP Event package message-summary
11266     MIME type defaults to  "application/simple-message-summary";
11267  */
11268 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
11269 {
11270    struct sip_request req;
11271    struct ast_str *out = ast_str_alloca(500);
11272    int ourport = ntohs(p->ourip.sin_port);
11273    const char *exten = S_OR(vmexten, default_vmexten);
11274 
11275    initreqprep(&req, p, SIP_NOTIFY);
11276    add_header(&req, "Event", "message-summary");
11277    add_header(&req, "Content-Type", default_notifymime);
11278    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
11279 
11280    if (!ast_strlen_zero(p->fromdomain)) {
11281       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
11282    } else if (!sip_standard_port(p->socket.type, ourport)) {
11283       if (p->socket.type == SIP_TRANSPORT_UDP) {
11284          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
11285       } else {
11286          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport, get_transport(p->socket.type));
11287       }
11288    } else {
11289       if (p->socket.type == SIP_TRANSPORT_UDP) {
11290          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
11291       } else {
11292          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), get_transport(p->socket.type));
11293       }
11294    }
11295    /* Cisco has a bug in the SIP stack where it can't accept the
11296       (0/0) notification. This can temporarily be disabled in
11297       sip.conf with the "buggymwi" option */
11298    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
11299       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
11300 
11301    if (p->subscribed) {
11302       if (p->expiry)
11303          add_header(&req, "Subscription-State", "active");
11304       else  /* Expired */
11305          add_header(&req, "Subscription-State", "terminated;reason=timeout");
11306    }
11307 
11308    add_header_contentLength(&req, out->used);
11309    add_line(&req, out->str);
11310 
11311    if (!p->initreq.headers) 
11312       initialize_initreq(p, &req);
11313    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11314 }
11315 
11316 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
11317 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
11318 {
11319    struct sip_request req;
11320    char tmp[SIPBUFSIZE/2];
11321    
11322    reqprep(&req, p, SIP_NOTIFY, 0, 1);
11323    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
11324    add_header(&req, "Event", tmp);
11325    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
11326    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
11327    add_header(&req, "Allow", ALLOWED_METHODS);
11328    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11329 
11330    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
11331    add_header_contentLength(&req, strlen(tmp));
11332    add_line(&req, tmp);
11333 
11334    if (!p->initreq.headers)
11335       initialize_initreq(p, &req);
11336 
11337    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11338 }
11339 
11340 /*! \brief Notify device with custom headers from sip_notify.conf */
11341 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
11342    struct sip_request req;
11343    struct ast_variable *var, *newvar;
11344 
11345    initreqprep(&req, p, SIP_NOTIFY);
11346 
11347    /* Copy notify vars and add headers */
11348    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
11349    add_header(&req, newvar->name, newvar->value);
11350    for (var = vars; var; var = var->next) {
11351       char buf[512];
11352       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
11353       ast_copy_string(buf, var->value, sizeof(buf));
11354       add_header(&req, var->name, ast_unescape_semicolon(buf));
11355       newvar->next = ast_variable_new(var->name, var->value, "");
11356       newvar = newvar->next;
11357    }
11358 
11359    if (!p->initreq.headers) { /* Initialize first request before sending */
11360       initialize_initreq(p, &req);
11361    }
11362 
11363    return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
11364 }
11365 
11366 static int manager_sipnotify(struct mansession *s, const struct message *m)
11367 {
11368    const char *channame = astman_get_header(m, "Channel");
11369    struct ast_variable *vars = astman_get_variables(m);
11370    struct sip_pvt *p;
11371 
11372    if (ast_strlen_zero(channame)) {
11373       astman_send_error(s, m, "SIPNotify requires a channel name");
11374       return 0;
11375    }
11376 
11377    if (!strncasecmp(channame, "sip/", 4)) {
11378       channame += 4;
11379    }
11380 
11381    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
11382       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
11383       return 0;
11384    }
11385 
11386    if (create_addr(p, channame, NULL, 0)) {
11387       /* Maybe they're not registered, etc. */
11388       dialog_unlink_all(p, TRUE, TRUE);
11389       dialog_unref(p, "unref dialog inside for loop" );
11390       /* sip_destroy(p); */
11391       astman_send_error(s, m, "Could not create address");
11392       return 0;
11393    }
11394 
11395    /* Notify is outgoing call */
11396    ast_set_flag(&p->flags[0], SIP_OUTGOING);
11397 
11398    /* Recalculate our side, and recalculate Call ID */
11399    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11400    build_via(p);
11401    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
11402    build_callid_pvt(p);
11403    ao2_t_link(dialogs, p, "Linking in new name");
11404    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
11405    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
11406 
11407    if (!transmit_notify_custom(p, vars)) {
11408       astman_send_ack(s, m, "Notify Sent");
11409    } else {
11410       astman_send_error(s, m, "Unable to send notify");
11411    }
11412    ast_variables_destroy(vars);
11413    return 0;
11414 }
11415 
11416 static char mandescr_sipnotify[] =
11417 "Description: Sends a SIP Notify event\n"
11418 "All parameters for this event must be specified in the body of this request\n"
11419 "via multiple Variable: name=value sequences.\n"
11420 "Variables: \n"
11421 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
11422 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
11423 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
11424 
11425 static const struct _map_x_s regstatestrings[] = {
11426    { REG_STATE_FAILED,     "Failed" },
11427    { REG_STATE_UNREGISTERED, "Unregistered"},
11428    { REG_STATE_REGSENT, "Request Sent"},
11429    { REG_STATE_AUTHSENT, "Auth. Sent"},
11430    { REG_STATE_REGISTERED, "Registered"},
11431    { REG_STATE_REJECTED, "Rejected"},
11432    { REG_STATE_TIMEOUT, "Timeout"},
11433    { REG_STATE_NOAUTH, "No Authentication"},
11434    { -1, NULL } /* terminator */
11435 };
11436 
11437 /*! \brief Convert registration state status to string */
11438 static const char *regstate2str(enum sipregistrystate regstate)
11439 {
11440    return map_x_s(regstatestrings, regstate, "Unknown");
11441 }
11442 
11443 /*! \brief Update registration with SIP Proxy.
11444  * Called from the scheduler when the previous registration expires,
11445  * so we don't have to cancel the pending event.
11446  * We assume the reference so the sip_registry is valid, since it
11447  * is stored in the scheduled event anyways.
11448  */
11449 static int sip_reregister(const void *data) 
11450 {
11451    /* if we are here, we know that we need to reregister. */
11452    struct sip_registry *r= (struct sip_registry *) data;
11453 
11454    /* if we couldn't get a reference to the registry object, punt */
11455    if (!r)
11456       return 0;
11457 
11458    if (r->call && r->call->do_history)
11459       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
11460    /* Since registry's are only added/removed by the the monitor thread, this
11461       may be overkill to reference/dereference at all here */
11462    if (sipdebug)
11463       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
11464 
11465    r->expire = -1;
11466    r->expiry = r->configured_expiry;
11467    __sip_do_register(r);
11468    registry_unref(r, "unref the re-register scheduled event");
11469    return 0;
11470 }
11471 
11472 /*! \brief Register with SIP proxy */
11473 static int __sip_do_register(struct sip_registry *r)
11474 {
11475    int res;
11476 
11477    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
11478    return res;
11479 }
11480 
11481 /*! \brief Registration timeout, register again
11482  * Registered as a timeout handler during transmit_register(),
11483  * to retransmit the packet if a reply does not come back.
11484  * This is called by the scheduler so the event is not pending anymore when
11485  * we are called.
11486  */
11487 static int sip_reg_timeout(const void *data)
11488 {
11489 
11490    /* if we are here, our registration timed out, so we'll just do it over */
11491    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
11492    struct sip_pvt *p;
11493    int res;
11494 
11495    /* if we couldn't get a reference to the registry object, punt */
11496    if (!r)
11497       return 0;
11498 
11499    if (r->dnsmgr) {
11500       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
11501       ast_dnsmgr_refresh(r->dnsmgr);
11502    }
11503 
11504    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
11505    /* If the initial tranmission failed, we may not have an existing dialog,
11506     * so it is possible that r->call == NULL.
11507     * Otherwise destroy it, as we have a timeout so we don't want it.
11508     */
11509    if (r->call) {
11510       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
11511          in the single SIP manager thread. */
11512       p = r->call;
11513       sip_pvt_lock(p);
11514       pvt_set_needdestroy(p, "registration timeout");
11515       /* Pretend to ACK anything just in case */
11516       __sip_pretend_ack(p);
11517       sip_pvt_unlock(p);
11518 
11519       /* decouple the two objects */
11520       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
11521       if (p->registry)
11522          p->registry = registry_unref(p->registry, "p->registry unreffed");
11523       r->call = dialog_unref(r->call, "unrefing r->call");
11524    }
11525    /* If we have a limit, stop registration and give up */
11526    r->timeout = -1;
11527    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
11528       /* Ok, enough is enough. Don't try any more */
11529       /* We could add an external notification here... 
11530          steal it from app_voicemail :-) */
11531       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
11532       r->regstate = REG_STATE_FAILED;
11533    } else {
11534       r->regstate = REG_STATE_UNREGISTERED;
11535       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
11536    }
11537    manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
11538    registry_unref(r, "unreffing registry_unref r");
11539    return 0;
11540 }
11541 
11542 /*! \brief Transmit register to SIP proxy or UA
11543  * auth = NULL on the initial registration (from sip_reregister())
11544  */
11545 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
11546 {
11547    struct sip_request req;
11548    char from[256];
11549    char to[256];
11550    char tmp[80];
11551    char addr[80];
11552    struct sip_pvt *p;
11553    struct sip_peer *peer = NULL;
11554    int res;
11555    char *fromdomain;
11556    char *domainport = NULL;
11557 
11558    /* exit if we are already in process with this registrar ?*/
11559    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
11560       if (r) {
11561          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
11562       }
11563       return 0;
11564    }
11565 
11566    if (r->dnsmgr == NULL) {
11567       char transport[MAXHOSTNAMELEN];
11568       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
11569       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
11570       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL);
11571       if (peer) {
11572          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
11573       }
11574    }
11575 
11576    if (r->call) { /* We have a registration */
11577       if (!auth) {
11578          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
11579          return 0;
11580       } else {
11581          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
11582          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
11583          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
11584       }
11585    } else {
11586       /* Build callid for registration if we haven't registered before */
11587       if (!r->callid_valid) {
11588          build_callid_registry(r, internip.sin_addr, default_fromdomain);
11589          r->callid_valid = TRUE;
11590       }
11591       /* Allocate SIP dialog for registration */
11592       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
11593          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
11594          return 0;
11595       }
11596       
11597       if (p->do_history)
11598          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
11599 
11600       if (!ast_strlen_zero(r->peername)) {
11601          if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE, 0))) {
11602             ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
11603          } else {
11604             p->peerauth = peer->auth;
11605          }
11606       }
11607       ref_proxy(p, obproxy_get(p, peer)); /* it is ok to pass a NULL peer into obproxy_get() */
11608       if (peer) {
11609          unref_peer(peer, "transmit_registration: from find_peer operation");
11610       }
11611       /* Use port number specified if no SRV record was found */
11612       if (!r->us.sin_port && r->portno)
11613          r->us.sin_port = htons(r->portno);
11614 
11615       /* Find address to hostname */
11616       if (create_addr(p, r->hostname, &r->us, 0)) {
11617          /* we have what we hope is a temporary network error,
11618           * probably DNS.  We need to reschedule a registration try */
11619          dialog_unlink_all(p, TRUE, TRUE);
11620          p = dialog_unref(p, "unref dialog after unlink_all");
11621          if (r->timeout > -1) {
11622             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11623                               registry_unref(_data, "del for REPLACE of registry ptr"), 
11624                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
11625                               registry_addref(r,"add for REPLACE registry ptr"));
11626             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
11627          } else {
11628             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
11629             ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
11630          }
11631          r->regattempts++;
11632          return 0;
11633       }
11634 
11635       /* Copy back Call-ID in case create_addr changed it */
11636       ast_string_field_set(r, callid, p->callid);
11637       if (!r->dnsmgr && r->portno) {
11638          p->sa.sin_port = htons(r->portno);
11639          p->recv.sin_port = htons(r->portno);
11640       } else { /* Set registry port to the port set from the peer definition/srv or default */
11641          r->portno = ntohs(p->sa.sin_port);
11642       }
11643       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
11644       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
11645       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
11646       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
11647          ast_string_field_set(p, peersecret, r->secret);
11648       }
11649       if (!ast_strlen_zero(r->md5secret))
11650          ast_string_field_set(p, peermd5secret, r->md5secret);
11651       /* User name in this realm  
11652       - if authuser is set, use that, otherwise use username */
11653       if (!ast_strlen_zero(r->authuser)) {   
11654          ast_string_field_set(p, peername, r->authuser);
11655          ast_string_field_set(p, authname, r->authuser);
11656       } else if (!ast_strlen_zero(r->username)) {
11657          ast_string_field_set(p, peername, r->username);
11658          ast_string_field_set(p, authname, r->username);
11659          ast_string_field_set(p, fromuser, r->username);
11660       }
11661       if (!ast_strlen_zero(r->username))
11662          ast_string_field_set(p, username, r->username);
11663       /* Save extension in packet */
11664       if (!ast_strlen_zero(r->callback))
11665          ast_string_field_set(p, exten, r->callback);
11666 
11667       /* Set transport and port so the correct contact is built */
11668       set_socket_transport(&p->socket, r->transport);
11669       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
11670          p->socket.port = sip_tcp_desc.local_address.sin_port;
11671       }
11672 
11673       /*
11674         check which address we should use in our contact header 
11675         based on whether the remote host is on the external or
11676         internal network so we can register through nat
11677        */
11678       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
11679       build_contact(p);
11680    }
11681 
11682    /* set up a timeout */
11683    if (auth == NULL)  {
11684       if (r->timeout > -1)
11685          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
11686       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
11687                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
11688                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
11689                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
11690       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
11691    }
11692 
11693    if ((fromdomain = strchr(r->username, '@'))) {
11694       /* the domain name is just behind '@' */
11695       fromdomain++ ;
11696       /* We have a domain in the username for registration */
11697       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
11698       if (!ast_strlen_zero(p->theirtag))
11699          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
11700       else
11701          snprintf(to, sizeof(to), "<sip:%s>", r->username);
11702 
11703       /* If the registration username contains '@', then the domain should be used as
11704          the equivalent of "fromdomain" for the registration */
11705       if (ast_strlen_zero(p->fromdomain)) {
11706          ast_string_field_set(p, fromdomain, fromdomain);
11707       }
11708    } else {
11709       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
11710       if (!ast_strlen_zero(p->theirtag))
11711          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
11712       else
11713          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
11714    }
11715    
11716    /* Fromdomain is what we are registering to, regardless of actual
11717       host name from SRV */
11718    if (!ast_strlen_zero(p->fromdomain)) {
11719       domainport = strrchr(p->fromdomain, ':');
11720       if (domainport) {
11721          *domainport++ = '\0'; /* trim off domainport from p->fromdomain */
11722          if (ast_strlen_zero(domainport))
11723             domainport = NULL;
11724       }     
11725       if (domainport) {       
11726          if (atoi(domainport) != STANDARD_SIP_PORT)
11727             snprintf(addr, sizeof(addr), "sip:%s:%s", p->fromdomain, domainport);
11728          else
11729             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11730       } else {
11731          if (r->portno && r->portno != STANDARD_SIP_PORT)
11732             snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
11733          else
11734             snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
11735       }
11736    } else {
11737       if (r->portno && r->portno != STANDARD_SIP_PORT)
11738          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
11739       else
11740          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
11741    }
11742    ast_string_field_set(p, uri, addr);
11743 
11744    p->branch ^= ast_random();
11745 
11746    init_req(&req, sipmethod, addr);
11747 
11748    /* Add to CSEQ */
11749    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
11750    p->ocseq = r->ocseq;
11751 
11752    build_via(p);
11753    add_header(&req, "Via", p->via);
11754    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
11755    add_header(&req, "From", from);
11756    add_header(&req, "To", to);
11757    add_header(&req, "Call-ID", p->callid);
11758    add_header(&req, "CSeq", tmp);
11759    if (!ast_strlen_zero(global_useragent))
11760       add_header(&req, "User-Agent", global_useragent);
11761 
11762    
11763    if (auth)   /* Add auth header */
11764       add_header(&req, authheader, auth);
11765    else if (!ast_strlen_zero(r->nonce)) {
11766       char digest[1024];
11767 
11768       /* We have auth data to reuse, build a digest header.
11769        * Note, this is not always useful because some parties do not
11770        * like nonces to be reused (for good reasons!) so they will
11771        * challenge us anyways.
11772        */
11773       if (sipdebug)
11774          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
11775       ast_string_field_set(p, realm, r->realm);
11776       ast_string_field_set(p, nonce, r->nonce);
11777       ast_string_field_set(p, domain, r->domain);
11778       ast_string_field_set(p, opaque, r->opaque);
11779       ast_string_field_set(p, qop, r->qop);
11780       p->noncecount = ++r->noncecount;
11781 
11782       memset(digest, 0, sizeof(digest));
11783       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
11784          add_header(&req, "Authorization", digest);
11785       else
11786          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
11787    
11788    }
11789 
11790    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11791    add_header(&req, "Expires", tmp);
11792    add_header(&req, "Contact", p->our_contact);
11793    add_header_contentLength(&req, 0);
11794 
11795    initialize_initreq(p, &req);
11796    if (sip_debug_test_pvt(p)) {
11797       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11798    }
11799    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11800    r->regattempts++; /* Another attempt */
11801    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11802    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11803    dialog_unref(p, "p is finished here at the end of transmit_register");
11804    return res;
11805 }
11806 
11807 /*! \brief Transmit text with SIP MESSAGE method */
11808 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11809 {
11810    struct sip_request req;
11811    
11812    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11813    add_text(&req, text);
11814    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11815 }
11816 
11817 /*! \brief Allocate SIP refer structure */
11818 static int sip_refer_allocate(struct sip_pvt *p)
11819 {
11820    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11821    return p->refer ? 1 : 0;
11822 }
11823 
11824 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11825    \note this is currently broken as we have no way of telling the dialplan
11826    engine whether a transfer succeeds or fails.
11827    \todo Fix the transfer() dialplan function so that a transfer may fail
11828 */
11829 static int transmit_refer(struct sip_pvt *p, const char *dest)
11830 {
11831    struct sip_request req = { 
11832       .headers = 0,  
11833    };
11834    char from[256];
11835    const char *of;
11836    char *c;
11837    char referto[256];
11838    char *ttag, *ftag;
11839    char *theirtag = ast_strdupa(p->theirtag);
11840    int   use_tls=FALSE;
11841 
11842    if (sipdebug)
11843       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11844 
11845    /* Are we transfering an inbound or outbound call ? */
11846    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
11847       of = get_header(&p->initreq, "To");
11848       ttag = theirtag;
11849       ftag = p->tag;
11850    } else {
11851       of = get_header(&p->initreq, "From");
11852       ftag = theirtag;
11853       ttag = p->tag;
11854    }
11855 
11856    ast_copy_string(from, of, sizeof(from));
11857    of = get_in_brackets(from);
11858    ast_string_field_set(p, from, of);
11859    if (!strncasecmp(of, "sip:", 4)) {
11860       of += 4;
11861    }else if (!strncasecmp(of, "sips:", 5)) {
11862       of += 5;
11863       use_tls = TRUE;
11864    } else {
11865       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
11866    }
11867    /* Get just the username part */
11868    if ((c = strchr(dest, '@')))
11869       c = NULL;
11870    else if ((c = strchr(of, '@')))
11871       *c++ = '\0';
11872    if (c) 
11873       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
11874    else
11875       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
11876 
11877    /* save in case we get 407 challenge */
11878    sip_refer_allocate(p);
11879    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11880    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11881    p->refer->status = REFER_SENT;   /* Set refer status */
11882 
11883    reqprep(&req, p, SIP_REFER, 0, 1);
11884 
11885    add_header(&req, "Refer-To", referto);
11886    add_header(&req, "Allow", ALLOWED_METHODS);
11887    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11888    if (!ast_strlen_zero(p->our_contact))
11889       add_header(&req, "Referred-By", p->our_contact);
11890 
11891    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11892 
11893    /* We should propably wait for a NOTIFY here until we ack the transfer */
11894    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
11895 
11896    /*! \todo In theory, we should hang around and wait for a reply, before
11897    returning to the dial plan here. Don't know really how that would
11898    affect the transfer() app or the pbx, but, well, to make this
11899    useful we should have a STATUS code on transfer().
11900    */
11901 }
11902 
11903 
11904 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
11905 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11906 {
11907    struct sip_request req;
11908    
11909    reqprep(&req, p, SIP_INFO, 0, 1);
11910    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11911    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11912 }
11913 
11914 /*! \brief Send SIP INFO with video update request */
11915 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11916 {
11917    struct sip_request req;
11918    
11919    reqprep(&req, p, SIP_INFO, 0, 1);
11920    add_vidupdate(&req);
11921    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11922 }
11923 
11924 /*! \brief Transmit generic SIP request 
11925    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
11926 */
11927 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11928 {
11929    struct sip_request resp;
11930    
11931    if (sipmethod == SIP_ACK)
11932       p->invitestate = INV_CONFIRMED;
11933 
11934    reqprep(&resp, p, sipmethod, seqno, newbranch);
11935    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
11936       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
11937 
11938    add_header_contentLength(&resp, 0);
11939    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11940 }
11941 
11942 /*! \brief return the request and response heade for a 401 or 407 code */
11943 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
11944 {
11945    if (code == WWW_AUTH) {       /* 401 */
11946       *header = "WWW-Authenticate";
11947       *respheader = "Authorization";
11948    } else if (code == PROXY_AUTH) { /* 407 */
11949       *header = "Proxy-Authenticate";
11950       *respheader = "Proxy-Authorization";
11951    } else {
11952       ast_verbose("-- wrong response code %d\n", code);
11953       *header = *respheader = "Invalid";
11954    }
11955 }
11956 
11957 /*! \brief Transmit SIP request, auth added */
11958 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11959 {
11960    struct sip_request resp;
11961    
11962    reqprep(&resp, p, sipmethod, seqno, newbranch);
11963    if (!ast_strlen_zero(p->realm)) {
11964       char digest[1024];
11965 
11966       memset(digest, 0, sizeof(digest));
11967       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
11968          char *dummy, *response;
11969          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
11970          auth_headers(code, &dummy, &response);
11971          add_header(&resp, response, digest);
11972       } else
11973          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
11974    }
11975    /* If we are hanging up and know a cause for that, send it in clear text to make
11976       debugging easier. */
11977    if (sipmethod == SIP_BYE)  {
11978       char buf[10];
11979 
11980       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
11981       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
11982       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
11983    }
11984 
11985    add_header_contentLength(&resp, 0);
11986    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
11987 }
11988 
11989 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
11990 static void destroy_association(struct sip_peer *peer)
11991 {
11992    int realtimeregs = ast_check_realtime("sipregs");
11993    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
11994 
11995    if (!sip_cfg.ignore_regexpire) {
11996       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
11997          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
11998       } else {
11999          ast_db_del("SIP/Registry", peer->name);
12000       }
12001    }
12002 }
12003 
12004 static void set_socket_transport(struct sip_socket *socket, int transport)
12005 {
12006    /* if the transport type changes, clear all socket data */
12007    if (socket->type != transport) {
12008       socket->fd = -1;
12009       socket->type = transport;
12010       if (socket->tcptls_session) {
12011          ao2_ref(socket->tcptls_session, -1);
12012          socket->tcptls_session = NULL;
12013       }
12014    }
12015 }
12016 
12017 /*! \brief Expire registration of SIP peer */
12018 static int expire_register(const void *data)
12019 {
12020    struct sip_peer *peer = (struct sip_peer *)data;
12021 
12022    if (!peer)     /* Hmmm. We have no peer. Weird. */
12023       return 0;
12024 
12025    peer->expire = -1;
12026    peer->portinuri = 0;
12027    memset(&peer->addr, 0, sizeof(peer->addr));
12028 
12029    destroy_association(peer); /* remove registration data from storage */
12030    set_socket_transport(&peer->socket, peer->default_outbound_transport);
12031 
12032    if (peer->socket.tcptls_session) {
12033       ao2_ref(peer->socket.tcptls_session, -1);
12034       peer->socket.tcptls_session = NULL;
12035    }
12036 
12037    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
12038    register_peer_exten(peer, FALSE);   /* Remove regexten */
12039    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12040 
12041    /* Do we need to release this peer from memory? 
12042       Only for realtime peers and autocreated peers
12043    */
12044    if (peer->is_realtime)
12045       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
12046 
12047    if (peer->selfdestruct ||
12048        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
12049       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
12050       if (peer->addr.sin_addr.s_addr) {
12051          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12052       }
12053    }
12054 
12055    unref_peer(peer, "removing peer ref for expire_register");
12056 
12057    return 0;
12058 }
12059 
12060 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
12061 static int sip_poke_peer_s(const void *data)
12062 {
12063    struct sip_peer *peer = (struct sip_peer *)data;
12064 
12065    peer->pokeexpire = -1;
12066 
12067    sip_poke_peer(peer, 0);
12068 
12069    unref_peer(peer, "removing poke peer ref");
12070 
12071    return 0;
12072 }
12073 
12074 /*! \brief Get registration details from Asterisk DB */
12075 static void reg_source_db(struct sip_peer *peer)
12076 {
12077    char data[256];
12078    struct in_addr in;
12079    int expire;
12080    int port;
12081    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
12082 
12083    if (peer->rt_fromcontact) 
12084       return;
12085    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
12086       return;
12087 
12088    scan = data;
12089    addr = strsep(&scan, ":");
12090    port_str = strsep(&scan, ":");
12091    expiry_str = strsep(&scan, ":");
12092    username = strsep(&scan, ":");
12093    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
12094 
12095    if (!inet_aton(addr, &in))
12096       return;
12097 
12098    if (port_str)
12099       port = atoi(port_str);
12100    else
12101       return;
12102 
12103    if (expiry_str)
12104       expire = atoi(expiry_str);
12105    else
12106       return;
12107 
12108    if (username)
12109       ast_string_field_set(peer, username, username);
12110    if (contact)
12111       ast_string_field_set(peer, fullcontact, contact);
12112 
12113    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
12114        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
12115 
12116    memset(&peer->addr, 0, sizeof(peer->addr));
12117    peer->addr.sin_family = AF_INET;
12118    peer->addr.sin_addr = in;
12119    peer->addr.sin_port = htons(port);
12120    if (sipsock < 0) {
12121       /* SIP isn't up yet, so schedule a poke only, pretty soon */
12122       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
12123             unref_peer(_data, "removing poke peer ref"),
12124             unref_peer(peer, "removing poke peer ref"),
12125             ref_peer(peer, "adding poke peer ref"));
12126    } else {
12127       sip_poke_peer(peer, 0);
12128    }
12129    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
12130          unref_peer(_data, "remove registration ref"),
12131          unref_peer(peer, "remove registration ref"),
12132          ref_peer(peer, "add registration ref"));
12133    register_peer_exten(peer, TRUE);
12134 }
12135 
12136 /*! \brief Save contact header for 200 OK on INVITE */
12137 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
12138 {
12139    char contact[SIPBUFSIZE]; 
12140    char *c;
12141 
12142    /* Look for brackets */
12143    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12144    c = get_in_brackets(contact);
12145 
12146    /* Save full contact to call pvt for later bye or re-invite */
12147    ast_string_field_set(pvt, fullcontact, c);
12148 
12149    /* Save URI for later ACKs, BYE or RE-invites */
12150    ast_string_field_set(pvt, okcontacturi, c);
12151 
12152    /* We should return false for URI:s we can't handle,
12153       like tel:, mailto:,ldap: etc */
12154    return TRUE;      
12155 }
12156 
12157 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
12158 {
12159    struct hostent *hp;
12160    struct ast_hostent ahp;
12161    int port = STANDARD_SIP_PORT;
12162    char *host, *pt, *transport;
12163    char contact_buf[256];
12164    char *contact;
12165 
12166    /* Work on a copy */
12167    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
12168    contact = contact_buf;
12169 
12170    /* 
12171     * We have only the part in <brackets> here so we just need to parse a SIP URI.
12172     *
12173     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
12174     * We still need to be able to send to the remote agent through the proxy.
12175     */
12176 
12177    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
12178       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
12179    }
12180 
12181    /* set port */
12182    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
12183       port = port_str2int(pt, STANDARD_TLS_PORT);
12184    } else {
12185       port = port_str2int(pt, STANDARD_SIP_PORT);
12186    }
12187 
12188 
12189    /* XXX This could block for a long time XXX */
12190    /* We should only do this if it's a name, not an IP */
12191    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
12192       to find transport, port address and hostname. If there's a port number, we have to
12193       assume that the domain part is a host name and only look for an A/AAAA record in DNS.
12194    */
12195    hp = ast_gethostbyname(host, &ahp);
12196    if (!hp)  {
12197       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
12198       return -1;
12199    }
12200    sin->sin_family = AF_INET;
12201    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
12202    sin->sin_port = htons(port);
12203 
12204    return 0;
12205 }
12206 
12207 /*! \brief Change the other partys IP address based on given contact */
12208 static int set_address_from_contact(struct sip_pvt *pvt)
12209 {
12210    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
12211       /* NAT: Don't trust the contact field.  Just use what they came to us
12212          with. */
12213       /*! \todo We need to save the TRANSPORT here too */
12214       pvt->sa = pvt->recv;
12215       return 0;
12216    }
12217 
12218    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
12219 }
12220 
12221 /*! \brief Parse contact header and save registration (peer registration) */
12222 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
12223 {
12224    char contact[SIPBUFSIZE];
12225    char data[SIPBUFSIZE];
12226    const char *expires = get_header(req, "Expires");
12227    int expire = atoi(expires);
12228    char *curi, *host, *pt, *transport;
12229    int port;
12230    int transport_type;
12231    const char *useragent;
12232    struct hostent *hp;
12233    struct ast_hostent ahp;
12234    struct sockaddr_in oldsin, testsin;
12235 
12236 
12237    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
12238 
12239    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
12240       char *s = strcasestr(contact, ";expires=");
12241       if (s) {
12242          expires = strsep(&s, ";"); /* trim ; and beyond */
12243          if (sscanf(expires + 9, "%30d", &expire) != 1)
12244             expire = default_expiry;
12245       } else {
12246          /* Nothing has been specified */
12247          expire = default_expiry;
12248       }
12249    }
12250 
12251    copy_socket_data(&pvt->socket, &req->socket);
12252 
12253    /* Look for brackets */
12254    curi = contact;
12255    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
12256       strsep(&curi, ";");  /* This is Header options, not URI options */
12257    curi = get_in_brackets(contact);
12258 
12259    /* if they did not specify Contact: or Expires:, they are querying
12260       what we currently have stored as their contact address, so return
12261       it
12262    */
12263    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
12264       /* If we have an active registration, tell them when the registration is going to expire */
12265       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
12266          pvt->expiry = ast_sched_when(sched, peer->expire);
12267       return PARSE_REGISTER_QUERY;
12268    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
12269       /* This means remove all registrations and return OK */
12270       memset(&peer->addr, 0, sizeof(peer->addr));
12271       set_socket_transport(&peer->socket, peer->default_outbound_transport);
12272 
12273       AST_SCHED_DEL_UNREF(sched, peer->expire,
12274             unref_peer(peer, "remove register expire ref"));
12275 
12276       destroy_association(peer);
12277 
12278       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
12279       ast_string_field_set(peer, fullcontact, "");
12280       ast_string_field_set(peer, useragent, "");
12281       peer->sipoptions = 0;
12282       peer->lastms = 0;
12283       peer->portinuri = 0;
12284       pvt->expiry = 0;
12285 
12286       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
12287 
12288       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
12289       return PARSE_REGISTER_UPDATE;
12290    }
12291 
12292    /* Store whatever we got as a contact from the client */
12293    ast_string_field_set(peer, fullcontact, curi);
12294 
12295    /* For the 200 OK, we should use the received contact */
12296    ast_string_field_build(pvt, our_contact, "<%s>", curi);
12297 
12298    /* Make sure it's a SIP URL */
12299    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
12300       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
12301    }
12302 
12303    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
12304       The domain part is actually a host. */
12305    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
12306 
12307    /* handle the transport type specified in Contact header. */
12308    if ((transport_type = get_transport_str2enum(transport))) {
12309       /* if the port is not specified but the transport is, make sure to set the
12310        * default port to match the specified transport.  This may or may not be the
12311        * same transport used by the pvt struct for the Register dialog. */
12312       
12313       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
12314    } else {
12315       port = port_str2int(pt, STANDARD_SIP_PORT);
12316       transport_type = pvt->socket.type;
12317    }
12318 
12319    /* if the peer's socket type is different than the Registration
12320     * transport type, change it.  If it got this far, it is a
12321     * supported type, but check just in case */
12322    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
12323       set_socket_transport(&peer->socket, transport_type);
12324    }
12325 
12326    oldsin = peer->addr;
12327 
12328    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
12329    if (peer->addr.sin_addr.s_addr) {
12330       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
12331    }
12332 
12333    /* Check that they're allowed to register at this IP */
12334    /* XXX This could block for a long time XXX */
12335    /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
12336    hp = ast_gethostbyname(host, &ahp);
12337    if (!hp)  {
12338       ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
12339       ast_string_field_set(peer, fullcontact, "");
12340       ast_string_field_set(pvt, our_contact, "");
12341       return PARSE_REGISTER_FAILED;
12342    }
12343    memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
12344    if (ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
12345          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
12346       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
12347       ast_string_field_set(peer, fullcontact, "");
12348       ast_string_field_set(pvt, our_contact, "");
12349       return PARSE_REGISTER_DENIED;
12350    }
12351 
12352    /*! \todo This could come before the checking of DNS earlier on, to avoid 
12353       DNS lookups where we don't need it... */
12354    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
12355       peer->addr.sin_family = AF_INET;
12356       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
12357       peer->addr.sin_port = htons(port);
12358    } else {
12359       /* Don't trust the contact field.  Just use what they came to us
12360          with */
12361       peer->addr = pvt->recv;
12362    }
12363 
12364    /* if the Contact header information copied into peer->addr matches the
12365     * received address, and the transport types are the same, then copy socket
12366     * data into the peer struct */
12367    if ((peer->socket.type == pvt->socket.type) &&
12368       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
12369       (peer->addr.sin_port == pvt->recv.sin_port)){
12370 
12371       copy_socket_data(&peer->socket, &pvt->socket);
12372    }
12373 
12374    /* Now that our address has been updated put ourselves back into the container for lookups */
12375    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
12376 
12377    /* Save SIP options profile */
12378    peer->sipoptions = pvt->sipoptions;
12379 
12380    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
12381       ast_string_field_set(peer, username, curi);
12382 
12383    AST_SCHED_DEL_UNREF(sched, peer->expire,
12384          unref_peer(peer, "remove register expire ref"));
12385 
12386    if (expire > max_expiry)
12387       expire = max_expiry;
12388    if (expire < min_expiry)
12389       expire = min_expiry;
12390    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
12391       peer->expire = -1;
12392    } else {
12393       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
12394             ref_peer(peer, "add registration ref"));
12395       if (peer->expire == -1) {
12396          unref_peer(peer, "remote registration ref");
12397       }
12398    }
12399    pvt->expiry = expire;
12400    snprintf(data, sizeof(data), "%s:%d:%d:%s:%s", ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port), expire, peer->username, peer->fullcontact);
12401    /* Saving TCP connections is useless, we won't be able to reconnect 
12402       XXX WHY???? XXX
12403       \todo Fix this immediately.
12404    */
12405    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
12406       ast_db_put("SIP/Registry", peer->name, data);
12407    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name,  ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
12408 
12409    /* Is this a new IP address for us? */
12410    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
12411       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d\n", peer->name, ast_inet_ntoa(peer->addr.sin_addr), ntohs(peer->addr.sin_port));
12412    }
12413    sip_poke_peer(peer, 0);
12414    register_peer_exten(peer, 1);
12415    
12416    /* Save User agent */
12417    useragent = get_header(req, "User-Agent");
12418    if (strcasecmp(useragent, peer->useragent)) {
12419       ast_string_field_set(peer, useragent, useragent);
12420       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
12421    }
12422    return PARSE_REGISTER_UPDATE;
12423 }
12424 
12425 /*! \brief Remove route from route list */
12426 static void free_old_route(struct sip_route *route)
12427 {
12428    struct sip_route *next;
12429 
12430    while (route) {
12431       next = route->next;
12432       ast_free(route);
12433       route = next;
12434    }
12435 }
12436 
12437 /*! \brief List all routes - mostly for debugging */
12438 static void list_route(struct sip_route *route)
12439 {
12440    if (!route)
12441       ast_verbose("list_route: no route\n");
12442    else {
12443       for (;route; route = route->next)
12444          ast_verbose("list_route: hop: <%s>\n", route->hop);
12445    }
12446 }
12447 
12448 /*! \brief Build route list from Record-Route header */
12449 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
12450 {
12451    struct sip_route *thishop, *head, *tail;
12452    int start = 0;
12453    int len;
12454    const char *rr, *contact, *c;
12455 
12456    /* Once a persistant route is set, don't fool with it */
12457    if (p->route && p->route_persistant) {
12458       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
12459       return;
12460    }
12461 
12462    if (p->route) {
12463       free_old_route(p->route);
12464       p->route = NULL;
12465    }
12466 
12467    /* We only want to create the route set the first time this is called */
12468    p->route_persistant = 1;
12469    
12470    /* Build a tailq, then assign it to p->route when done.
12471     * If backwards, we add entries from the head so they end up
12472     * in reverse order. However, we do need to maintain a correct
12473     * tail pointer because the contact is always at the end.
12474     */
12475    head = NULL;
12476    tail = head;
12477    /* 1st we pass through all the hops in any Record-Route headers */
12478    for (;;) {
12479       /* Each Record-Route header */
12480       rr = __get_header(req, "Record-Route", &start);
12481       if (*rr == '\0')
12482          break;
12483       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
12484          ++rr;
12485          len = strcspn(rr, ">") + 1;
12486          /* Make a struct route */
12487          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12488             /* ast_calloc is not needed because all fields are initialized in this block */
12489             ast_copy_string(thishop->hop, rr, len);
12490             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
12491             /* Link in */
12492             if (backwards) {
12493                /* Link in at head so they end up in reverse order */
12494                thishop->next = head;
12495                head = thishop;
12496                /* If this was the first then it'll be the tail */
12497                if (!tail)
12498                   tail = thishop;
12499             } else {
12500                thishop->next = NULL;
12501                /* Link in at the end */
12502                if (tail)
12503                   tail->next = thishop;
12504                else
12505                   head = thishop;
12506                tail = thishop;
12507             }
12508          }
12509       }
12510    }
12511 
12512    /* Only append the contact if we are dealing with a strict router */
12513    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
12514       /* 2nd append the Contact: if there is one */
12515       /* Can be multiple Contact headers, comma separated values - we just take the first */
12516       contact = get_header(req, "Contact");
12517       if (!ast_strlen_zero(contact)) {
12518          ast_debug(2, "build_route: Contact hop: %s\n", contact);
12519          /* Look for <: delimited address */
12520          c = strchr(contact, '<');
12521          if (c) {
12522             /* Take to > */
12523             ++c;
12524             len = strcspn(c, ">") + 1;
12525          } else {
12526             /* No <> - just take the lot */
12527             c = contact;
12528             len = strlen(contact) + 1;
12529          }
12530          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
12531             /* ast_calloc is not needed because all fields are initialized in this block */
12532             ast_copy_string(thishop->hop, c, len);
12533             thishop->next = NULL;
12534             /* Goes at the end */
12535             if (tail)
12536                tail->next = thishop;
12537             else
12538                head = thishop;
12539          }
12540       }
12541    }
12542 
12543    /* Store as new route */
12544    p->route = head;
12545 
12546    /* For debugging dump what we ended up with */
12547    if (sip_debug_test_pvt(p))
12548       list_route(p->route);
12549 }
12550 
12551 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
12552  *  challenge.  When forceupdate is not set, the nonce is only updated if
12553  *  the current one is stale.  In this case, a stalenonce is one which
12554  *  has already received a response, if a nonce has not received a response
12555  *  it is not always necessary or beneficial to create a new one. */
12556 
12557 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
12558 {
12559    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
12560       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
12561       p->stalenonce = 0;
12562    }
12563 }
12564 
12565 AST_THREADSTORAGE(check_auth_buf);
12566 #define CHECK_AUTH_BUF_INITLEN   256
12567 
12568 /*! \brief  Check user authorization from peer definition 
12569    Some actions, like REGISTER and INVITEs from peers require
12570    authentication (if peer have secret set) 
12571     \return 0 on success, non-zero on error
12572 */
12573 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
12574                 const char *secret, const char *md5secret, int sipmethod,
12575                 char *uri, enum xmittype reliable, int ignore)
12576 {
12577    const char *response;
12578    char *reqheader, *respheader;
12579    const char *authtoken;
12580    char a1_hash[256];
12581    char resp_hash[256]="";
12582    char *c;
12583    int  wrongnonce = FALSE;
12584    int  good_response;
12585    const char *usednonce = p->randdata;
12586    struct ast_str *buf;
12587    int res;
12588 
12589    /* table of recognised keywords, and their value in the digest */
12590    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
12591    struct x {
12592       const char *key;
12593       const char *s;
12594    } *i, keys[] = {
12595       [K_RESP] = { "response=", "" },
12596       [K_URI] = { "uri=", "" },
12597       [K_USER] = { "username=", "" },
12598       [K_NONCE] = { "nonce=", "" },
12599       [K_LAST] = { NULL, NULL}
12600    };
12601 
12602    /* Always OK if no secret */
12603    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
12604       return AUTH_SUCCESSFUL;
12605 
12606    /* Always auth with WWW-auth since we're NOT a proxy */
12607    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
12608    response = "401 Unauthorized";
12609 
12610    /*
12611     * Note the apparent swap of arguments below, compared to other
12612     * usages of auth_headers().
12613     */
12614    auth_headers(WWW_AUTH, &respheader, &reqheader);
12615 
12616    authtoken =  get_header(req, reqheader);  
12617    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12618       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12619          information */
12620       if (!reliable) {
12621          /* Resend message if this was NOT a reliable delivery.   Otherwise the
12622             retransmission should get it */
12623          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12624          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12625          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12626       }
12627       return AUTH_CHALLENGE_SENT;
12628    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12629       /* We have no auth, so issue challenge and request authentication */
12630       set_nonce_randdata(p, 1); /* Create nonce for challenge */
12631       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
12632       /* Schedule auto destroy in 32 seconds */
12633       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12634       return AUTH_CHALLENGE_SENT;
12635    } 
12636 
12637    /* --- We have auth, so check it */
12638 
12639    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
12640       an example in the spec of just what it is you're doing a hash on. */
12641 
12642    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
12643       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12644 
12645    /* Make a copy of the response and parse it */
12646    res = ast_str_set(&buf, 0, "%s", authtoken);
12647 
12648    if (res == AST_DYNSTR_BUILD_FAILED)
12649       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
12650 
12651    c = buf->str;
12652 
12653    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
12654       for (i = keys; i->key != NULL; i++) {
12655          const char *separator = ",";  /* default */
12656 
12657          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
12658             continue;
12659          /* Found. Skip keyword, take text in quotes or up to the separator. */
12660          c += strlen(i->key);
12661          if (*c == '"') { /* in quotes. Skip first and look for last */
12662             c++;
12663             separator = "\"";
12664          }
12665          i->s = c;
12666          strsep(&c, separator);
12667          break;
12668       }
12669       if (i->key == NULL) /* not found, jump after space or comma */
12670          strsep(&c, " ,");
12671    }
12672 
12673    /* Verify that digest username matches  the username we auth as */
12674    if (strcmp(username, keys[K_USER].s)) {
12675       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
12676          username, keys[K_USER].s);
12677       /* Oops, we're trying something here */
12678       return AUTH_USERNAME_MISMATCH;
12679    }
12680 
12681    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
12682     * If this check fails, send 401 with new nonce */
12683    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
12684       wrongnonce = TRUE;
12685       usednonce = keys[K_NONCE].s;
12686    } else {
12687       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
12688    }
12689 
12690    if (!ast_strlen_zero(md5secret))
12691       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
12692    else {
12693       char a1[256];
12694       snprintf(a1, sizeof(a1), "%s:%s:%s", username, sip_cfg.realm, secret);
12695       ast_md5_hash(a1_hash, a1);
12696    }
12697 
12698    /* compute the expected response to compare with what we received */
12699    {
12700       char a2[256];
12701       char a2_hash[256];
12702       char resp[256];
12703 
12704       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
12705             S_OR(keys[K_URI].s, uri));
12706       ast_md5_hash(a2_hash, a2);
12707       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
12708       ast_md5_hash(resp_hash, resp);
12709    }
12710 
12711    good_response = keys[K_RESP].s &&
12712          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
12713    if (wrongnonce) {
12714       if (good_response) {
12715          if (sipdebug)
12716             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
12717          /* We got working auth token, based on stale nonce . */
12718          set_nonce_randdata(p, 0);
12719          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
12720       } else {
12721          /* Everything was wrong, so give the device one more try with a new challenge */
12722          if (!req->ignore) {
12723             if (sipdebug)
12724                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
12725             set_nonce_randdata(p, 1);
12726          } else {
12727             if (sipdebug)
12728                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
12729          }
12730          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12731       }
12732 
12733       /* Schedule auto destroy in 32 seconds */
12734       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12735       return AUTH_CHALLENGE_SENT;
12736    } 
12737    if (good_response) {
12738       append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
12739       return AUTH_SUCCESSFUL;
12740    }
12741 
12742    /* Ok, we have a bad username/secret pair */
12743    /* Tell the UAS not to re-send this authentication data, because
12744       it will continue to fail
12745    */
12746 
12747    return AUTH_SECRET_FAILED;
12748 }
12749 
12750 /*! \brief Change onhold state of a peer using a pvt structure */
12751 static void sip_peer_hold(struct sip_pvt *p, int hold)
12752 {
12753    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
12754 
12755    if (!peer)
12756       return;
12757 
12758    /* If they put someone on hold, increment the value... otherwise decrement it */
12759    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
12760 
12761    /* Request device state update */
12762    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12763    unref_peer(peer, "sip_peer_hold: from find_peer operation");
12764    
12765    return;
12766 }
12767 
12768 /*! \brief Receive MWI events that we have subscribed to */
12769 static void mwi_event_cb(const struct ast_event *event, void *userdata)
12770 {
12771    struct sip_peer *peer = userdata;
12772 
12773    ao2_lock(peer);
12774    sip_send_mwi_to_peer(peer, event, 0);
12775    ao2_unlock(peer);
12776 }
12777 
12778 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
12779 \note If you add an "hint" priority to the extension in the dial plan,
12780    you will get notifications on device state changes */
12781 static int cb_extensionstate(char *context, char* exten, int state, void *data)
12782 {
12783    struct sip_pvt *p = data;
12784 
12785    sip_pvt_lock(p);
12786 
12787    switch(state) {
12788    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
12789    case AST_EXTENSION_REMOVED:   /* Extension is gone */
12790       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
12791          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12792       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
12793       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
12794       p->stateid = -1;
12795       p->subscribed = NONE;
12796       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
12797       break;
12798    default: /* Tell user */
12799       p->laststate = state;
12800       break;
12801    }
12802    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
12803       if (!p->pendinginvite) {
12804          transmit_state_notify(p, state, 1, FALSE);
12805       } else {
12806          /* We already have a NOTIFY sent that is not answered. Queue the state up.
12807             if many state changes happen meanwhile, we will only send a notification of the last one */
12808          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12809       }
12810    }
12811    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12812          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12813 
12814    sip_pvt_unlock(p);
12815 
12816    return 0;
12817 }
12818 
12819 /*! \brief Send a fake 401 Unauthorized response when the administrator
12820   wants to hide the names of local devices  from fishers
12821  */
12822 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12823 {
12824    /* We have to emulate EXACTLY what we'd get with a good peer
12825     * and a bad password, or else we leak information. */
12826    const char *response = "407 Proxy Authentication Required";
12827    const char *reqheader = "Proxy-Authorization";
12828    const char *respheader = "Proxy-Authenticate";
12829    const char *authtoken;
12830    struct ast_str *buf;
12831    char *c;
12832 
12833    /* table of recognised keywords, and their value in the digest */
12834    enum keys { K_NONCE, K_LAST };
12835    struct x {
12836       const char *key;
12837       const char *s;
12838    } *i, keys[] = {
12839       [K_NONCE] = { "nonce=", "" },
12840       [K_LAST] = { NULL, NULL}
12841    };
12842 
12843    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12844       response = "401 Unauthorized";
12845       reqheader = "Authorization";
12846       respheader = "WWW-Authenticate";
12847    }
12848    authtoken = get_header(req, reqheader);
12849    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12850       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12851        * information */
12852       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12853       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12854       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12855       return;
12856    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12857       /* We have no auth, so issue challenge and request authentication */
12858       set_nonce_randdata(p, 1);
12859       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12860       /* Schedule auto destroy in 32 seconds */
12861       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12862       return;
12863    }
12864 
12865    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12866       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12867       return;
12868    }
12869 
12870    /* Make a copy of the response and parse it */
12871    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12872       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12873       return;
12874    }
12875 
12876    c = buf->str;
12877 
12878    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
12879       for (i = keys; i->key != NULL; i++) {
12880          const char *separator = ",";  /* default */
12881 
12882          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12883             continue;
12884          }
12885          /* Found. Skip keyword, take text in quotes or up to the separator. */
12886          c += strlen(i->key);
12887          if (*c == '"') { /* in quotes. Skip first and look for last */
12888             c++;
12889             separator = "\"";
12890          }
12891          i->s = c;
12892          strsep(&c, separator);
12893          break;
12894       }
12895       if (i->key == NULL) { /* not found, jump after space or comma */
12896          strsep(&c, " ,");
12897       }
12898    }
12899 
12900    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
12901    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12902       if (!req->ignore) {
12903          set_nonce_randdata(p, 1);
12904       }
12905       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12906 
12907       /* Schedule auto destroy in 32 seconds */
12908       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12909    } else {
12910       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12911    }
12912 }
12913 
12914 /*!
12915  * Terminate the uri at the first ';' or space.
12916  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
12917  * but don't do it for the time being. Remember the uri format is:
12918  * (User-parameters was added after RFC 3261)
12919  *\verbatim
12920  *
12921  * sip:user:password;user-parameters@host:port;uri-parameters?headers
12922  * sips:user:password;user-parameters@host:port;uri-parameters?headers
12923  *
12924  *\endverbatim
12925  * \todo As this function does not support user-parameters, it's considered broken
12926  * and needs fixing.
12927  */
12928 static char *terminate_uri(char *uri)
12929 {
12930    char *t = uri;
12931    while (*t && *t > ' ' && *t != ';')
12932       t++;
12933    *t = '\0';
12934    return uri;
12935 }
12936 
12937 /*! \brief Verify registration of user 
12938    - Registration is done in several steps, first a REGISTER without auth
12939      to get a challenge (nonce) then a second one with auth
12940    - Registration requests are only matched with peers that are marked as "dynamic"
12941  */
12942 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
12943                      struct sip_request *req, char *uri)
12944 {
12945    enum check_auth_result res = AUTH_NOT_FOUND;
12946    struct sip_peer *peer;
12947    char tmp[256];
12948    char *name, *c;
12949    char *domain;
12950 
12951    terminate_uri(uri);  /* warning, overwrite the string */
12952 
12953    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
12954    if (sip_cfg.pedanticsipchecking)
12955       ast_uri_decode(tmp);
12956 
12957    c = get_in_brackets(tmp);
12958    c = remove_uri_parameters(c);
12959 
12960    if (!strncasecmp(c, "sip:", 4)) {
12961       name = c + 4;
12962    } else if (!strncasecmp(c, "sips:", 5)) {
12963       name = c + 5;
12964    } else {
12965       name = c;
12966       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
12967    }
12968 
12969    /*! \todo XXX here too we interpret a missing @domain as a name-only
12970     * URI, whereas the RFC says this is a domain-only uri.
12971     */
12972    /* Strip off the domain name */
12973    if ((c = strchr(name, '@'))) {
12974       *c++ = '\0';
12975       domain = c;
12976       if ((c = strchr(domain, ':')))   /* Remove :port */
12977          *c = '\0';
12978       if (!AST_LIST_EMPTY(&domain_list)) {
12979          if (!check_sip_domain(domain, NULL, 0)) {
12980             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
12981             return AUTH_UNKNOWN_DOMAIN;
12982          }
12983       }
12984    }
12985    c = strchr(name, ';');  /* Remove any Username parameters */
12986    if (c)
12987       *c = '\0';
12988 
12989    ast_string_field_set(p, exten, name);
12990    build_contact(p);
12991    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
12992    if (!(peer && ast_apply_ha(peer->ha, sin))) {
12993       /* Peer fails ACL check */
12994       if (peer) {
12995          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
12996          peer = NULL;
12997          res = AUTH_ACL_FAILED;
12998       } else
12999          res = AUTH_NOT_FOUND;
13000    }
13001 
13002    if (peer) {
13003       /*! \todo OEJ Remove this - there's never RTP in a REGISTER dialog... */
13004       /* Set Frame packetization */
13005       if (p->rtp) {
13006          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13007          p->autoframing = peer->autoframing;
13008       }
13009       if (!peer->host_dynamic) {
13010          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
13011          res = AUTH_PEER_NOT_DYNAMIC;
13012       } else {
13013          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
13014          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
13015             transmit_response(p, "100 Trying", req);
13016          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
13017             if (sip_cancel_destroy(p))
13018                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13019 
13020             if (check_request_transport(peer, req)) {
13021                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
13022                transmit_response_with_date(p, "403 Forbidden", req);
13023                res = AUTH_BAD_TRANSPORT;
13024             } else {
13025 
13026                /* We have a successful registration attempt with proper authentication,
13027                   now, update the peer */
13028                switch (parse_register_contact(p, peer, req)) {
13029                case PARSE_REGISTER_DENIED:
13030                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13031                   transmit_response_with_date(p, "603 Denied", req);
13032                   peer->lastmsgssent = -1;
13033                   res = 0;
13034                   break;
13035                case PARSE_REGISTER_FAILED:
13036                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
13037                   transmit_response_with_date(p, "400 Bad Request", req);
13038                   peer->lastmsgssent = -1;
13039                   res = 0;
13040                   break;
13041                case PARSE_REGISTER_QUERY:
13042                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13043                   transmit_response_with_date(p, "200 OK", req);
13044                   peer->lastmsgssent = -1;
13045                   res = 0;
13046                   break;
13047                case PARSE_REGISTER_UPDATE:
13048                   ast_string_field_set(p, fullcontact, peer->fullcontact);
13049                   update_peer(peer, p->expiry);
13050                   /* Say OK and ask subsystem to retransmit msg counter */
13051                   transmit_response_with_date(p, "200 OK", req);
13052                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
13053                      peer->lastmsgssent = -1;
13054                   res = 0;
13055                   break;
13056                }
13057             }
13058 
13059          } 
13060       }
13061    }
13062    if (!peer && sip_cfg.autocreatepeer) {
13063       /* Create peer if we have autocreate mode enabled */
13064       peer = temp_peer(name);
13065       if (peer) {
13066          ao2_t_link(peers, peer, "link peer into peer table");
13067          if (peer->addr.sin_addr.s_addr) {
13068             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
13069          }
13070          
13071          if (sip_cancel_destroy(p))
13072             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
13073          switch (parse_register_contact(p, peer, req)) {
13074          case PARSE_REGISTER_DENIED:
13075             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
13076             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
13077             peer->lastmsgssent = -1;
13078             res = 0;
13079             break;
13080          case PARSE_REGISTER_FAILED:
13081             ast_log(LOG_WARNING, "Failed to parse contact info\n");
13082             transmit_response_with_date(p, "400 Bad Request", req);
13083             peer->lastmsgssent = -1;
13084             res = 0;
13085             break;
13086          case PARSE_REGISTER_QUERY:
13087             ast_string_field_set(p, fullcontact, peer->fullcontact);
13088             transmit_response_with_date(p, "200 OK", req);
13089             peer->lastmsgssent = -1;
13090             res = 0;
13091             break;
13092          case PARSE_REGISTER_UPDATE:
13093             ast_string_field_set(p, fullcontact, peer->fullcontact);
13094             /* Say OK and ask subsystem to retransmit msg counter */
13095             transmit_response_with_date(p, "200 OK", req);
13096             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\nPort: %d\r\n", peer->name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13097             peer->lastmsgssent = -1;
13098             res = 0;
13099             break;
13100          }
13101       }
13102    }
13103    if (!peer && sip_cfg.alwaysauthreject) {
13104       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
13105        * trying to avoid leaking information, we MUST also transmit the same
13106        * response when we DON'T find a peer. */
13107       transmit_response(p, "100 Trying", req);
13108       /* Insert a fake delay between the 100 and the subsequent failure. */
13109       sched_yield();
13110    }
13111    if (!res) {
13112       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13113    }
13114    if (res < 0) {
13115       switch (res) {
13116       case AUTH_SECRET_FAILED:
13117          /* Wrong password in authentication. Go away, don't try again until you fixed it */
13118          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
13119          if (global_authfailureevents)
13120             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_SECRET_FAILED\r\nAddress: %s\r\nPort: %d\r\n", 
13121                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13122          break;
13123       case AUTH_USERNAME_MISMATCH:
13124          /* Username and digest username does not match.
13125             Asterisk uses the From: username for authentication. We need the
13126             devices to use the same authentication user name until we support
13127             proper authentication by digest auth name */
13128       case AUTH_NOT_FOUND:
13129       case AUTH_PEER_NOT_DYNAMIC:
13130       case AUTH_ACL_FAILED:
13131          if (sip_cfg.alwaysauthreject) {
13132             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
13133             if (global_authfailureevents) {
13134                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n",
13135                   name, res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
13136                   ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13137             }
13138          } else {
13139             /* URI not found */
13140             if (res == AUTH_PEER_NOT_DYNAMIC) {
13141                transmit_response(p, "403 Forbidden", &p->initreq);
13142                if (global_authfailureevents)
13143                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: AUTH_PEER_NOT_DYNAMIC\r\nAddress: %s\r\nPort: %d\r\n", 
13144                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13145                }
13146             else
13147                transmit_response(p, "404 Not found", &p->initreq);
13148                if (global_authfailureevents)
13149                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Rejected\r\nCause: %s\r\nAddress: %s\r\nPort: %d\r\n", 
13150                            name, (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
13151          }
13152          break;
13153       case AUTH_BAD_TRANSPORT:
13154       default:
13155          break;
13156       }
13157    }
13158    if (peer)
13159       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
13160 
13161    return res;
13162 }
13163 
13164 /*! \brief Translate referring cause */
13165 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
13166 
13167    if (!strcmp(reason, "unknown")) {
13168       ast_string_field_set(p, redircause, "UNKNOWN");
13169    } else if (!strcmp(reason, "user-busy")) {
13170       ast_string_field_set(p, redircause, "BUSY");
13171    } else if (!strcmp(reason, "no-answer")) {
13172       ast_string_field_set(p, redircause, "NOANSWER");
13173    } else if (!strcmp(reason, "unavailable")) {
13174       ast_string_field_set(p, redircause, "UNREACHABLE");
13175    } else if (!strcmp(reason, "unconditional")) {
13176       ast_string_field_set(p, redircause, "UNCONDITIONAL");
13177    } else if (!strcmp(reason, "time-of-day")) {
13178       ast_string_field_set(p, redircause, "UNKNOWN");
13179    } else if (!strcmp(reason, "do-not-disturb")) {
13180       ast_string_field_set(p, redircause, "UNKNOWN");
13181    } else if (!strcmp(reason, "deflection")) {
13182       ast_string_field_set(p, redircause, "UNKNOWN");
13183    } else if (!strcmp(reason, "follow-me")) {
13184       ast_string_field_set(p, redircause, "UNKNOWN");
13185    } else if (!strcmp(reason, "out-of-service")) {
13186       ast_string_field_set(p, redircause, "UNREACHABLE");
13187    } else if (!strcmp(reason, "away")) {
13188       ast_string_field_set(p, redircause, "UNREACHABLE");
13189    } else {
13190       ast_string_field_set(p, redircause, "UNKNOWN");
13191    }
13192 }
13193 
13194 /*! \brief Get referring dnis */
13195 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
13196 {
13197    char tmp[256], *exten, *rexten, *rdomain;
13198    char *params, *reason = NULL;
13199    struct sip_request *req;
13200    
13201    req = oreq ? oreq : &p->initreq;
13202 
13203    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
13204    if (ast_strlen_zero(tmp))
13205       return 0;
13206 
13207    /*! \todo This function does not take user-parameters into consideration.
13208       First look for @, then start looking for ; to find uri-parameters.
13209    */
13210    params = strchr(tmp, ';');
13211 
13212    exten = get_in_brackets(tmp);
13213    if (!strncasecmp(exten, "sip:", 4)) {
13214       exten += 4;
13215    } else if (!strncasecmp(exten, "sips:", 5)) {
13216       exten += 5;
13217    } else {
13218       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
13219       return -1;
13220    }
13221 
13222    /* Get diversion-reason param if present */
13223    if (params) {
13224       *params = '\0';   /* Cut off parameters  */
13225       params++;
13226       while (*params == ';' || *params == ' ')
13227          params++;
13228       /* Check if we have a reason parameter */
13229       if ((reason = strcasestr(params, "reason="))) {
13230          reason+=7;
13231          /* Remove enclosing double-quotes */
13232          if (*reason == '"') 
13233             ast_strip_quoted(reason, "\"", "\"");
13234          if (!ast_strlen_zero(reason)) {
13235             sip_set_redirstr(p, reason);
13236             if (p->owner) {
13237                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
13238                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
13239             }
13240          }
13241       }
13242    }
13243 
13244    rdomain = exten;
13245    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
13246    if (p->owner) 
13247       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
13248 
13249    if (sip_debug_test_pvt(p))
13250       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
13251 
13252    ast_string_field_set(p, rdnis, rexten);
13253 
13254    return 0;
13255 }
13256 
13257 /*! \brief Find out who the call is for.
13258    We use the request uri as a destination. 
13259    This code assumes authentication has been done, so that the
13260    device (peer/user) context is already set.
13261    \return 0 on success (found a matching extension),
13262    1 for pickup extension or overlap dialling support (if we support it),
13263    -1 on error.
13264 
13265   \note If the incoming uri is a SIPS: uri, we are required to carry this across
13266    the dialplan, so that the outbound call also is a sips: call or encrypted
13267    IAX2 call. If that's not available, the call should FAIL.
13268 */
13269 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
13270 {
13271    char tmp[256] = "", *uri, *a;
13272    char tmpf[256] = "", *from = NULL;
13273    struct sip_request *req;
13274    char *colon;
13275    char *decoded_uri;
13276    
13277    req = oreq;
13278    if (!req)
13279       req = &p->initreq;
13280 
13281    /* Find the request URI */
13282    if (req->rlPart2)
13283       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
13284    
13285    if (sip_cfg.pedanticsipchecking)
13286       ast_uri_decode(tmp);
13287 
13288    uri = get_in_brackets(tmp);
13289    
13290    if (!strncasecmp(uri, "sip:", 4)) {
13291       uri += 4;
13292    } else if (!strncasecmp(uri, "sips:", 5)) {
13293       uri += 5;
13294    } else {
13295       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
13296       return -1;
13297    }
13298 
13299    /* Now find the From: caller ID and name */
13300    /* XXX Why is this done in get_destination? Isn't it already done?
13301       Needs to be checked 
13302         */
13303    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
13304    if (!ast_strlen_zero(tmpf)) {
13305       if (sip_cfg.pedanticsipchecking)
13306          ast_uri_decode(tmpf);
13307       from = get_in_brackets(tmpf);
13308    } 
13309    
13310    if (!ast_strlen_zero(from)) {
13311       if (!strncasecmp(from, "sip:", 4)) {
13312          from += 4;
13313       } else if (!strncasecmp(from, "sips:", 5)) {
13314          from += 5;
13315       } else {
13316          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
13317          return -1;
13318       }
13319       if ((a = strchr(from, '@')))
13320          *a++ = '\0';
13321       else
13322          a = from;   /* just a domain */
13323       from = strsep(&from, ";"); /* Remove userinfo options */
13324       a = strsep(&a, ";");    /* Remove URI options */
13325       ast_string_field_set(p, fromdomain, a);
13326    }
13327 
13328    /* Skip any options and find the domain */
13329 
13330    /* Get the target domain */
13331    if ((a = strchr(uri, '@'))) {
13332       *a++ = '\0';
13333    } else { /* No username part */
13334       a = uri;
13335       uri = "s";  /* Set extension to "s" */
13336    }
13337    colon = strchr(a, ':'); /* Remove :port */
13338    if (colon)
13339       *colon = '\0';
13340 
13341    uri = strsep(&uri, ";");   /* Remove userinfo options */
13342    a = strsep(&a, ";");    /* Remove URI options */
13343 
13344    ast_string_field_set(p, domain, a);
13345 
13346    if (!AST_LIST_EMPTY(&domain_list)) {
13347       char domain_context[AST_MAX_EXTENSION];
13348 
13349       domain_context[0] = '\0';
13350       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
13351          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
13352             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
13353             return -2;
13354          }
13355       }
13356       /* If we have a context defined, overwrite the original context */
13357       if (!ast_strlen_zero(domain_context))
13358          ast_string_field_set(p, context, domain_context);
13359    }
13360 
13361    /* If the request coming in is a subscription and subscribecontext has been specified use it */
13362    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
13363       ast_string_field_set(p, context, p->subscribecontext);
13364 
13365    if (sip_debug_test_pvt(p))
13366       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
13367 
13368    /* If this is a subscription we actually just need to see if a hint exists for the extension */
13369    if (req->method == SIP_SUBSCRIBE) {
13370       char hint[AST_MAX_EXTENSION];
13371       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
13372    } else {
13373       decoded_uri = ast_strdupa(uri);
13374       ast_uri_decode(decoded_uri);
13375       /* Check the dialplan for the username part of the request URI,
13376          the domain will be stored in the SIPDOMAIN variable
13377          Since extensions.conf can have unescaped characters, try matching a decoded
13378          uri in addition to the non-decoded uri
13379          Return 0 if we have a matching extension */
13380       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from)) || ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from)) ||
13381           !strcmp(decoded_uri, ast_pickup_ext())) {
13382          if (!oreq)
13383             ast_string_field_set(p, exten, decoded_uri);
13384          return 0;
13385       } 
13386    }
13387 
13388    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
13389    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
13390        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
13391        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
13392       return 1;
13393    }
13394    
13395    return -1;
13396 }
13397 
13398 /*! \brief Lock dialog lock and find matching pvt lock  
13399    \return a reference, remember to release it when done 
13400 */
13401 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
13402 {
13403    struct sip_pvt *sip_pvt_ptr;
13404    struct sip_pvt tmp_dialog = {
13405       .callid = callid,
13406    };
13407 
13408    if (totag)
13409       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
13410 
13411    /* Search dialogs and find the match */
13412    
13413    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
13414    if (sip_pvt_ptr) {
13415       /* Go ahead and lock it (and its owner) before returning */
13416       sip_pvt_lock(sip_pvt_ptr);
13417       if (sip_cfg.pedanticsipchecking) {
13418          unsigned char frommismatch = 0, tomismatch = 0;
13419 
13420          if (ast_strlen_zero(fromtag)) {
13421             sip_pvt_unlock(sip_pvt_ptr);
13422             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
13423                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13424             return NULL;
13425          }
13426 
13427          if (ast_strlen_zero(totag)) {
13428             sip_pvt_unlock(sip_pvt_ptr);
13429             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
13430                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
13431             return NULL;
13432          }
13433          /* RFC 3891
13434           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
13435           * > The Replaces header contains information used to match an existing
13436           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
13437           * > with a Replaces header, the User Agent (UA) attempts to match this
13438           * > information with a confirmed or early dialog.  The User Agent Server
13439           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
13440           * > present in an incoming request.  In other words, the to-tag parameter
13441           * > is compared to the local tag, and the from-tag parameter is compared
13442           * > to the remote tag.
13443           *
13444           * Thus, the totag is always compared to the local tag, regardless if
13445           * this our call is an incoming or outgoing call.
13446           */
13447          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
13448          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
13449 
13450          if (frommismatch || tomismatch) {
13451             sip_pvt_unlock(sip_pvt_ptr);
13452             if (frommismatch) {
13453                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
13454                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13455                     fromtag, sip_pvt_ptr->theirtag);
13456             }
13457             if (tomismatch) {
13458                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
13459                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
13460                     totag, sip_pvt_ptr->tag);
13461             }
13462             return NULL;
13463          }
13464       }
13465       
13466       if (totag)
13467          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
13468                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
13469                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
13470 
13471       /* deadlock avoidance... */
13472       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
13473          sip_pvt_unlock(sip_pvt_ptr);
13474          usleep(1);
13475          sip_pvt_lock(sip_pvt_ptr);
13476       }
13477    }
13478    
13479    return sip_pvt_ptr;
13480 }
13481 
13482 /*! \brief Call transfer support (the REFER method) 
13483  *    Extracts Refer headers into pvt dialog structure 
13484  *
13485  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
13486  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
13487  * flag.
13488  */
13489 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
13490 {
13491 
13492    const char *p_referred_by = NULL;
13493    char *h_refer_to = NULL; 
13494    char *h_referred_by = NULL;
13495    char *refer_to;
13496    const char *p_refer_to;
13497    char *referred_by_uri = NULL;
13498    char *ptr;
13499    struct sip_request *req = NULL;
13500    const char *transfer_context = NULL;
13501    struct sip_refer *referdata;
13502 
13503 
13504    req = outgoing_req;
13505    referdata = transferer->refer;
13506 
13507    if (!req)
13508       req = &transferer->initreq;
13509 
13510    p_refer_to = get_header(req, "Refer-To");
13511    if (ast_strlen_zero(p_refer_to)) {
13512       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
13513       return -2;  /* Syntax error */
13514    }
13515    h_refer_to = ast_strdupa(p_refer_to);
13516    refer_to = get_in_brackets(h_refer_to);
13517    if (sip_cfg.pedanticsipchecking)
13518       ast_uri_decode(refer_to);
13519 
13520    if (!strncasecmp(refer_to, "sip:", 4)) {
13521       refer_to += 4;       /* Skip sip: */
13522    } else if (!strncasecmp(refer_to, "sips:", 5)) {
13523       refer_to += 5;
13524    } else {
13525       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
13526       return -3;
13527    }
13528 
13529    /* Get referred by header if it exists */
13530    p_referred_by = get_header(req, "Referred-By");
13531 
13532    /* Give useful transfer information to the dialplan */
13533    if (transferer->owner) {
13534       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
13535       if (peer) {
13536          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
13537          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
13538       }
13539    }
13540 
13541    if (!ast_strlen_zero(p_referred_by)) {
13542       char *lessthan;
13543       h_referred_by = ast_strdupa(p_referred_by);
13544       if (sip_cfg.pedanticsipchecking)
13545          ast_uri_decode(h_referred_by);
13546 
13547       /* Store referrer's caller ID name */
13548       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
13549       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
13550          *(lessthan - 1) = '\0'; /* Space */
13551       }
13552 
13553       referred_by_uri = get_in_brackets(h_referred_by);
13554       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
13555          referred_by_uri += 4;      /* Skip sip: */
13556       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
13557          referred_by_uri += 5;      /* Skip sips: */
13558       } else {
13559          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
13560          referred_by_uri = NULL;
13561       }
13562    }
13563 
13564    /* Check for arguments in the refer_to header */
13565    if ((ptr = strcasestr(refer_to, "replaces="))) {
13566       char *to = NULL, *from = NULL;
13567       
13568       /* This is an attended transfer */
13569       referdata->attendedtransfer = 1;
13570       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
13571       ast_uri_decode(referdata->replaces_callid);
13572       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
13573          *ptr++ = '\0';
13574       }
13575       
13576       if (ptr) {
13577          /* Find the different tags before we destroy the string */
13578          to = strcasestr(ptr, "to-tag=");
13579          from = strcasestr(ptr, "from-tag=");
13580       }
13581       
13582       /* Grab the to header */
13583       if (to) {
13584          ptr = to + 7;
13585          if ((to = strchr(ptr, '&')))
13586             *to = '\0';
13587          if ((to = strchr(ptr, ';')))
13588             *to = '\0';
13589          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
13590       }
13591       
13592       if (from) {
13593          ptr = from + 9;
13594          if ((to = strchr(ptr, '&')))
13595             *to = '\0';
13596          if ((to = strchr(ptr, ';')))
13597             *to = '\0';
13598          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
13599       }
13600       
13601       if (!sip_cfg.pedanticsipchecking)
13602          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
13603       else
13604          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
13605    }
13606    
13607    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
13608       char *urioption = NULL, *domain;
13609       *ptr++ = '\0';
13610 
13611       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
13612          *urioption++ = '\0';
13613       
13614       domain = ptr;
13615       if ((ptr = strchr(domain, ':'))) /* Remove :port */
13616          *ptr = '\0';
13617       
13618       /* Save the domain for the dial plan */
13619       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
13620       if (urioption)
13621          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
13622    }
13623 
13624    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
13625       *ptr = '\0';
13626    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
13627    
13628    if (referred_by_uri) {
13629       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
13630          *ptr = '\0';
13631       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
13632    } else {
13633       referdata->referred_by[0] = '\0';
13634    }
13635 
13636    /* Determine transfer context */
13637    if (transferer->owner)  /* Mimic behaviour in res_features.c */
13638       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
13639 
13640    /* By default, use the context in the channel sending the REFER */
13641    if (ast_strlen_zero(transfer_context)) {
13642       transfer_context = S_OR(transferer->owner->macrocontext,
13643                S_OR(transferer->context, sip_cfg.default_context));
13644    }
13645 
13646    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
13647    
13648    /* Either an existing extension or the parking extension */
13649    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
13650       if (sip_debug_test_pvt(transferer)) {
13651          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
13652       }
13653       /* We are ready to transfer to the extension */
13654       return 0;
13655    } 
13656    if (sip_debug_test_pvt(transferer))
13657       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
13658 
13659    /* Failure, we can't find this extension */
13660    return -1;
13661 }
13662 
13663 
13664 /*! \brief Call transfer support (old way, deprecated by the IETF)
13665  * \note does not account for SIPS: uri requirements, nor check transport
13666  */
13667 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
13668 {
13669    char tmp[256] = "", *c, *a;
13670    struct sip_request *req = oreq ? oreq : &p->initreq;
13671    struct sip_refer *referdata = NULL;
13672    const char *transfer_context = NULL;
13673    
13674    if (!p->refer && !sip_refer_allocate(p))
13675       return -1;
13676 
13677    referdata = p->refer;
13678 
13679    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
13680    c = get_in_brackets(tmp);
13681 
13682    if (sip_cfg.pedanticsipchecking)
13683       ast_uri_decode(c);
13684 
13685    if (!strncasecmp(c, "sip:", 4)) {
13686       c += 4;
13687    } else if (!strncasecmp(c, "sips:", 5)) {
13688       c += 5;
13689    } else {
13690       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
13691       return -1;
13692    }
13693 
13694    if ((a = strchr(c, ';')))  /* Remove arguments */
13695       *a = '\0';
13696    
13697    if ((a = strchr(c, '@'))) {   /* Separate Domain */
13698       *a++ = '\0';
13699       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
13700    }
13701    
13702    if (sip_debug_test_pvt(p))
13703       ast_verbose("Looking for %s in %s\n", c, p->context);
13704 
13705    if (p->owner)  /* Mimic behaviour in res_features.c */
13706       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
13707 
13708    /* By default, use the context in the channel sending the REFER */
13709    if (ast_strlen_zero(transfer_context)) {
13710       transfer_context = S_OR(p->owner->macrocontext,
13711                S_OR(p->context, sip_cfg.default_context));
13712    }
13713    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
13714       /* This is a blind transfer */
13715       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
13716       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
13717       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
13718       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
13719       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
13720       /* Set new context */
13721       ast_string_field_set(p, context, transfer_context);
13722       return 0;
13723    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
13724       return 1;
13725    }
13726 
13727    return -1;
13728 }
13729 
13730 /*! \brief check received= and rport= in a SIP response.
13731  * If we get a response with received= and/or rport= in the Via:
13732  * line, use them as 'p->ourip' (see RFC 3581 for rport,
13733  * and RFC 3261 for received).
13734  * Using these two fields SIP can produce the correct
13735  * address and port in the SIP headers without the need for STUN.
13736  * The address part is also reused for the media sessions.
13737  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
13738  * if you specify externip/seternaddr/stunaddr.
13739  */
13740 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
13741 {
13742    char via[256];
13743    char *cur, *opts;
13744 
13745    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13746 
13747    /* Work on the leftmost value of the topmost Via header */
13748    opts = strchr(via, ',');
13749    if (opts)
13750       *opts = '\0';
13751 
13752    /* parse all relevant options */
13753    opts = strchr(via, ';');
13754    if (!opts)
13755       return;  /* no options to parse */
13756    *opts++ = '\0';
13757    while ( (cur = strsep(&opts, ";")) ) {
13758       if (!strncmp(cur, "rport=", 6)) {
13759          int port = strtol(cur+6, NULL, 10);
13760          /* XXX add error checking */
13761          p->ourip.sin_port = ntohs(port);
13762       } else if (!strncmp(cur, "received=", 9)) {
13763          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
13764             ;  /* XXX add error checking */
13765       }
13766    }
13767 }
13768 
13769 /*! \brief check Via: header for hostname, port and rport request/answer */
13770 static void check_via(struct sip_pvt *p, struct sip_request *req)
13771 {
13772    char via[512];
13773    char *c, *pt, *maddr;
13774    struct hostent *hp;
13775    struct ast_hostent ahp;
13776 
13777    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
13778 
13779    /* Work on the leftmost value of the topmost Via header */
13780    c = strchr(via, ',');
13781    if (c)
13782       *c = '\0';
13783 
13784    /* Check for rport */
13785    c = strstr(via, ";rport");
13786    if (c && (c[6] != '=')) /* rport query, not answer */
13787       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
13788 
13789    /* Check for maddr */
13790    maddr = strstr(via, "maddr=");
13791    if (maddr) {
13792       maddr += 6;
13793       c = maddr + strspn(maddr, "0123456789.");
13794       *c = '\0';
13795    }
13796 
13797    c = strchr(via, ';');
13798    if (c)
13799       *c = '\0';
13800 
13801    c = strchr(via, ' ');
13802    if (c) {
13803       *c = '\0';
13804       c = ast_skip_blanks(c+1);
13805       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
13806          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
13807          return;
13808       }
13809       pt = strchr(c, ':');
13810       if (pt)
13811          *pt++ = '\0';  /* remember port pointer */
13812       /* Use maddr if found */
13813       if (maddr)
13814          c = maddr;
13815       hp = ast_gethostbyname(c, &ahp);
13816       if (!hp) {
13817          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
13818          return;
13819       }
13820       memset(&p->sa, 0, sizeof(p->sa));
13821       p->sa.sin_family = AF_INET;
13822       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
13823       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
13824 
13825       if (sip_debug_test_pvt(p)) {
13826          const struct sockaddr_in *dst = sip_real_dst(p);
13827          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13828       }
13829    }
13830 }
13831 
13832 /*! \brief  Get caller id name from SIP headers */
13833 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13834 {
13835    const char *end = strchr(input, '<');  /* first_bracket */
13836    const char *tmp = strchr(input, '"');  /* first quote */
13837    int bytes = 0;
13838    int maxbytes = outputsize - 1;
13839 
13840    if (!end || end == input)  /* we require a part in brackets */
13841       return NULL;
13842 
13843    end--; /* move just before "<" */
13844 
13845    if (tmp && tmp <= end) {
13846       /* The quote (tmp) precedes the bracket (end+1).
13847        * Find the matching quote and return the content.
13848        */
13849       end = strchr(tmp+1, '"');
13850       if (!end)
13851          return NULL;
13852       bytes = (int) (end - tmp);
13853       /* protect the output buffer */
13854       if (bytes > maxbytes)
13855          bytes = maxbytes;
13856       ast_copy_string(output, tmp + 1, bytes);
13857    } else {
13858       /* No quoted string, or it is inside brackets. */
13859       /* clear the empty characters in the begining*/
13860       input = ast_skip_blanks(input);
13861       /* clear the empty characters in the end */
13862       while(*end && *end < 33 && end > input)
13863          end--;
13864       if (end >= input) {
13865          bytes = (int) (end - input) + 2;
13866          /* protect the output buffer */
13867          if (bytes > maxbytes)
13868             bytes = maxbytes;
13869          ast_copy_string(output, input, bytes);
13870       } else
13871          return NULL;
13872    }
13873    return output;
13874 }
13875 
13876 /*! \brief  Get caller id number from Remote-Party-ID header field 
13877  * Returns true if number should be restricted (privacy setting found)
13878  * output is set to NULL if no number found
13879  */
13880 static int get_rpid_num(const char *input, char *output, int maxlen)
13881 {
13882    char *start;
13883    char *end;
13884 
13885    start = strchr(input, ':');
13886    if (!start) {
13887       output[0] = '\0';
13888       return 0;
13889    }
13890    start++;
13891 
13892    /* we found "number" */
13893    ast_copy_string(output, start, maxlen);
13894    output[maxlen-1] = '\0';
13895 
13896    end = strchr(output, '@');
13897    if (end)
13898       *end = '\0';
13899    else
13900       output[0] = '\0';
13901    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13902       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13903 
13904    return 0;
13905 }
13906 
13907 
13908 /*! \brief helper function for check_{user|peer}_ok() */
13909 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
13910 {
13911    /* replace callerid if rpid found, and not restricted */
13912    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
13913       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
13914       if (!ast_strlen_zero(calleridname))
13915          ast_string_field_set(p, cid_name, calleridname);
13916       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13917          ast_shrink_phone_number(tmp);
13918       ast_string_field_set(p, cid_num, tmp);
13919    }
13920 }
13921 
13922 /*! \brief Validate device authentication */
13923 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
13924    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
13925    struct sip_peer **authpeer,
13926    enum xmittype reliable,
13927    char *rpid_num, char *calleridname, char *uri2)
13928 {
13929    enum check_auth_result res;
13930    int debug=sip_debug_test_addr(sin);
13931    struct sip_peer *peer;
13932 
13933    if (sipmethod == SIP_SUBSCRIBE) {
13934       /* For subscribes, match on device name only; for other methods,
13935       * match on IP address-port of the incoming request.
13936       */
13937       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
13938    } else {
13939       /* First find devices based on username (avoid all type=peer's) */
13940       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
13941 
13942       /* Then find devices based on IP */
13943       if (!peer) {
13944          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
13945       }
13946    }
13947 
13948    if (!peer) {
13949       if (debug)
13950          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
13951             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13952       return AUTH_DONT_KNOW;
13953    }
13954    if (!ast_apply_ha(peer->ha, sin)) {
13955       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
13956       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
13957       return AUTH_ACL_FAILED;
13958    }
13959    if (debug)
13960       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
13961          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13962 
13963    /* XXX what about p->prefs = peer->prefs; ? */
13964    /* Set Frame packetization */
13965    if (p->rtp) {
13966       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13967       p->autoframing = peer->autoframing;
13968    }
13969 
13970    /* Take the peer */
13971    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
13972    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
13973 
13974    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
13975       p->t38_maxdatagram = peer->t38_maxdatagram;
13976       set_t38_capabilities(p);
13977    }
13978 
13979    /* Copy SIP extensions profile to peer */
13980    /* XXX is this correct before a successful auth ? */
13981    if (p->sipoptions)
13982       peer->sipoptions = p->sipoptions;
13983 
13984    replace_cid(p, rpid_num, calleridname);
13985    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
13986 
13987    ast_string_field_set(p, peersecret, peer->secret);
13988    ast_string_field_set(p, peermd5secret, peer->md5secret);
13989    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
13990    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
13991    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
13992    ast_string_field_set(p, parkinglot, peer->parkinglot);
13993    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
13994       p->callingpres = peer->callingpres;
13995    if (peer->maxms && peer->lastms)
13996       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
13997    else
13998       p->timer_t1 = peer->timer_t1;
13999  
14000    /* Set timer B to control transaction timeouts */
14001    if (peer->timer_b)
14002       p->timer_b = peer->timer_b;
14003    else
14004       p->timer_b = 64 * p->timer_t1;
14005  
14006    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
14007       /* Pretend there is no required authentication */
14008       ast_string_field_set(p, peersecret, NULL);
14009       ast_string_field_set(p, peermd5secret, NULL);
14010    }
14011    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
14012       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
14013       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
14014       /* If we have a call limit, set flag */
14015       if (peer->call_limit)
14016          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
14017       ast_string_field_set(p, peername, peer->name);
14018       ast_string_field_set(p, authname, peer->name);
14019 
14020       if (sipmethod == SIP_INVITE) {
14021          /* copy channel vars */
14022          p->chanvars = copy_vars(peer->chanvars);
14023       }
14024 
14025       if (authpeer) {
14026          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
14027          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
14028       }
14029 
14030       if (!ast_strlen_zero(peer->username)) {
14031          ast_string_field_set(p, username, peer->username);
14032          /* Use the default username for authentication on outbound calls */
14033          /* XXX this takes the name from the caller... can we override ? */
14034          ast_string_field_set(p, authname, peer->username);
14035       }
14036       if (!ast_strlen_zero(peer->cid_num)) {
14037          char *tmp = ast_strdupa(peer->cid_num);
14038          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14039             ast_shrink_phone_number(tmp);
14040          ast_string_field_set(p, cid_num, tmp);
14041       }
14042       if (!ast_strlen_zero(peer->cid_name)) 
14043          ast_string_field_set(p, cid_name, peer->cid_name);
14044       ast_string_field_set(p, fullcontact, peer->fullcontact);
14045       if (!ast_strlen_zero(peer->context))
14046          ast_string_field_set(p, context, peer->context);
14047       ast_string_field_set(p, peersecret, peer->secret);
14048       ast_string_field_set(p, peermd5secret, peer->md5secret);
14049       ast_string_field_set(p, language, peer->language);
14050       ast_string_field_set(p, accountcode, peer->accountcode);
14051       p->amaflags = peer->amaflags;
14052       p->callgroup = peer->callgroup;
14053       p->pickupgroup = peer->pickupgroup;
14054       p->capability = peer->capability;
14055       p->prefs = peer->prefs;
14056       p->jointcapability = peer->capability;
14057       if (p->peercapability)
14058          p->jointcapability &= p->peercapability;
14059       p->maxcallbitrate = peer->maxcallbitrate;
14060       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
14061             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
14062                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
14063             p->vrtp) {
14064          ast_rtp_destroy(p->vrtp);
14065          p->vrtp = NULL;
14066       }
14067       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
14068          ast_rtp_destroy(p->trtp);
14069          p->trtp = NULL;
14070       }
14071       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
14072           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
14073          p->noncodeccapability |= AST_RTP_DTMF;
14074       else
14075          p->noncodeccapability &= ~AST_RTP_DTMF;
14076       p->jointnoncodeccapability = p->noncodeccapability;
14077    }
14078    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
14079    return res;
14080 }
14081 
14082 
14083 /*! \brief  Check if matching user or peer is defined 
14084    Match user on From: user name and peer on IP/port
14085    This is used on first invite (not re-invites) and subscribe requests 
14086     \return 0 on success, non-zero on failure
14087 */
14088 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
14089                      int sipmethod, char *uri, enum xmittype reliable,
14090                      struct sockaddr_in *sin, struct sip_peer **authpeer)
14091 {
14092    char from[256];
14093    char *dummy;   /* dummy return value for parse_uri */
14094    char *domain;  /* dummy return value for parse_uri */
14095    char *of;
14096    char rpid_num[50];
14097    const char *rpid;
14098    enum check_auth_result res;
14099    char calleridname[50];
14100    char *uri2 = ast_strdupa(uri);
14101 
14102    terminate_uri(uri2); /* trim extra stuff */
14103 
14104    ast_copy_string(from, get_header(req, "From"), sizeof(from));
14105    if (sip_cfg.pedanticsipchecking)
14106       ast_uri_decode(from);
14107    /* XXX here tries to map the username for invite things */
14108    memset(calleridname, 0, sizeof(calleridname));
14109    get_calleridname(from, calleridname, sizeof(calleridname));
14110    if (calleridname[0])
14111       ast_string_field_set(p, cid_name, calleridname);
14112 
14113    rpid = get_header(req, "Remote-Party-ID");
14114    memset(rpid_num, 0, sizeof(rpid_num));
14115    if (!ast_strlen_zero(rpid)) 
14116       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
14117 
14118    of = get_in_brackets(from);
14119    if (ast_strlen_zero(p->exten)) {
14120       char *t = uri2;
14121       if (!strncasecmp(t, "sip:", 4))
14122          t+= 4;
14123       else if (!strncasecmp(t, "sips:", 5))
14124          t += 5;
14125       ast_string_field_set(p, exten, t);
14126       t = strchr(p->exten, '@');
14127       if (t)
14128          *t = '\0';
14129       if (ast_strlen_zero(p->our_contact))
14130          build_contact(p);
14131    }
14132    /* save the URI part of the From header */
14133    ast_string_field_set(p, from, of);
14134 
14135    /* ignore all fields but name */
14136    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
14137       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
14138    }
14139 
14140    if (ast_strlen_zero(of)) {
14141       /* XXX note: the original code considered a missing @host
14142        * as a username-only URI. The SIP RFC (19.1.1) says that
14143        * this is wrong, and it should be considered as a domain-only URI.
14144        * For backward compatibility, we keep this block, but it is
14145        * really a mistake and should go away.
14146        */
14147       of = domain;
14148    } else {
14149       char *tmp = ast_strdupa(of);
14150       /* We need to be able to handle auth-headers looking like
14151          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
14152       */
14153       tmp = strsep(&tmp, ";");
14154       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
14155          ast_shrink_phone_number(tmp);
14156       ast_string_field_set(p, cid_num, tmp);
14157    }
14158 
14159    if (global_match_auth_username) {
14160       /*
14161        * XXX This is experimental code to grab the search key from the
14162        * Auth header's username instead of the 'From' name, if available.
14163        * Do not enable this block unless you understand the side effects (if any!)
14164        * Note, the search for "username" should be done in a more robust way.
14165        * Note2, at the moment we check both fields, though maybe we should
14166        * pick one or another depending on the request ? XXX
14167        */
14168       const char *hdr = get_header(req, "Authorization");
14169       if (ast_strlen_zero(hdr))
14170          hdr = get_header(req, "Proxy-Authorization");
14171 
14172       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
14173          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
14174          of = from;
14175          of = strsep(&of, "\"");
14176       }
14177    }
14178 
14179    res = check_peer_ok(p, of, req, sipmethod, sin,
14180          authpeer, reliable, rpid_num, calleridname, uri2);
14181    if (res != AUTH_DONT_KNOW)
14182       return res;
14183 
14184    /* Finally, apply the guest policy */
14185    if (sip_cfg.allowguest) {
14186       replace_cid(p, rpid_num, calleridname);
14187       res = AUTH_SUCCESSFUL;
14188    } else if (sip_cfg.alwaysauthreject)
14189       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
14190    else
14191       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
14192 
14193 
14194    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
14195       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
14196    }
14197 
14198    return res;
14199 }
14200 
14201 /*! \brief  Find user 
14202    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
14203 */
14204 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
14205 {
14206    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
14207 }
14208 
14209 /*! \brief  Get text out of a SIP MESSAGE packet */
14210 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
14211 {
14212    int x;
14213    int y;
14214 
14215    buf[0] = '\0';
14216    /*XXX isn't strlen(buf) going to always be 0? */
14217    y = len - strlen(buf) - 5;
14218    if (y < 0)
14219       y = 0;
14220    for (x = 0; x < req->lines; x++) {
14221       char *line = REQ_OFFSET_TO_STR(req, line[x]);
14222       strncat(buf, line, y); /* safe */
14223       y -= strlen(line) + 1;
14224       if (y < 0)
14225          y = 0;
14226       if (y != 0 && addnewline)
14227          strcat(buf, "\n"); /* safe */
14228    }
14229    return 0;
14230 }
14231 
14232 
14233 /*! \brief  Receive SIP MESSAGE method messages
14234 \note We only handle messages within current calls currently 
14235    Reference: RFC 3428 */
14236 static void receive_message(struct sip_pvt *p, struct sip_request *req)
14237 {
14238    char buf[1400];   
14239    struct ast_frame f;
14240    const char *content_type = get_header(req, "Content-Type");
14241 
14242    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
14243       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
14244       if (!p->owner)
14245          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14246       return;
14247    }
14248 
14249    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
14250       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
14251       transmit_response(p, "202 Accepted", req);
14252       if (!p->owner)
14253          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14254       return;
14255    }
14256 
14257    if (p->owner) {
14258       if (sip_debug_test_pvt(p))
14259          ast_verbose("SIP Text message received: '%s'\n", buf);
14260       memset(&f, 0, sizeof(f));
14261       f.frametype = AST_FRAME_TEXT;
14262       f.subclass = 0;
14263       f.offset = 0;
14264       f.data.ptr = buf;
14265       f.datalen = strlen(buf);
14266       ast_queue_frame(p->owner, &f);
14267       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
14268       return;
14269    }
14270 
14271    /* Message outside of a call, we do not support that */
14272    ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
14273    transmit_response(p, "405 Method Not Allowed", req);
14274    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14275    return;
14276 }
14277 
14278 /*! \brief  CLI Command to show calls within limits set by call_limit */
14279 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14280 {
14281 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
14282 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
14283    char ilimits[40];
14284    char iused[40];
14285    int showall = FALSE;
14286    struct ao2_iterator i;
14287    struct sip_peer *peer;
14288    
14289    switch (cmd) {
14290    case CLI_INIT:
14291       e->command = "sip show inuse";
14292       e->usage =
14293          "Usage: sip show inuse [all]\n"
14294          "       List all SIP devices usage counters and limits.\n"
14295          "       Add option \"all\" to show all devices, not only those with a limit.\n";
14296       return NULL;
14297    case CLI_GENERATE:
14298       return NULL;
14299    }
14300 
14301    if (a->argc < 3) 
14302       return CLI_SHOWUSAGE;
14303 
14304    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
14305       showall = TRUE;
14306    
14307    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
14308 
14309    i = ao2_iterator_init(peers, 0);
14310    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
14311       ao2_lock(peer);
14312       if (peer->call_limit)
14313          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
14314       else 
14315          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
14316       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
14317       if (showall || peer->call_limit)
14318          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
14319       ao2_unlock(peer);
14320       unref_peer(peer, "toss iterator pointer");
14321    }
14322    ao2_iterator_destroy(&i);
14323 
14324    return CLI_SUCCESS;
14325 #undef FORMAT
14326 #undef FORMAT2
14327 }
14328 
14329 
14330 /*! \brief Convert transfer mode to text string */
14331 static char *transfermode2str(enum transfermodes mode)
14332 {
14333    if (mode == TRANSFER_OPENFORALL)
14334       return "open";
14335    else if (mode == TRANSFER_CLOSED)
14336       return "closed";
14337    return "strict";
14338 }
14339 
14340 static struct _map_x_s natmodes[] = {
14341    { SIP_NAT_NEVER,        "No"},
14342    { SIP_NAT_ROUTE,        "Route"},
14343    { SIP_NAT_ALWAYS,       "Always"},
14344    { SIP_NAT_RFC3581,      "RFC3581"},
14345    { -1,                   NULL}, /* terminator */
14346 };
14347 
14348 /*! \brief  Convert NAT setting to text string */
14349 static const char *nat2str(int nat)
14350 {
14351    return map_x_s(natmodes, nat, "Unknown");
14352 }
14353 
14354 #ifdef NOTUSED
14355 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
14356    delete it. Keeping it enabled generates compiler warnings.
14357  */
14358 
14359 static struct _map_x_s natcfgmodes[] = {
14360    { SIP_NAT_NEVER,        "never"},
14361    { SIP_NAT_ROUTE,        "route"},
14362    { SIP_NAT_ALWAYS,       "yes"},
14363    { SIP_NAT_RFC3581,      "no"},
14364    { -1,                   NULL}, /* terminator */
14365 };
14366 
14367 /*! \brief  Convert NAT setting to text string appropriate for config files */
14368 static const char *nat2strconfig(int nat)
14369 {
14370    return map_x_s(natcfgmodes, nat, "Unknown");
14371 }
14372 #endif
14373 
14374 /*! \brief  Report Peer status in character string
14375  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
14376  */
14377 
14378 
14379 /* Session-Timer Modes */
14380 static struct _map_x_s stmodes[] = {
14381         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
14382         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
14383         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
14384         { -1,                           NULL},
14385 };
14386 
14387 static const char *stmode2str(enum st_mode m)
14388 {
14389    return map_x_s(stmodes, m, "Unknown");
14390 }
14391 
14392 static enum st_mode str2stmode(const char *s)
14393 {
14394    return map_s_x(stmodes, s, -1);
14395 }
14396 
14397 /* Session-Timer Refreshers */
14398 static struct _map_x_s strefreshers[] = {
14399         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
14400         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
14401         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
14402         { -1,                               NULL},
14403 };
14404 
14405 static const char *strefresher2str(enum st_refresher r)
14406 {
14407    return map_x_s(strefreshers, r, "Unknown");
14408 }
14409 
14410 static enum st_refresher str2strefresher(const char *s)
14411 {
14412    return map_s_x(strefreshers, s, -1);
14413 }
14414 
14415 
14416 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
14417 {
14418    int res = 0;
14419    if (peer->maxms) {
14420       if (peer->lastms < 0) {
14421          ast_copy_string(status, "UNREACHABLE", statuslen);
14422       } else if (peer->lastms > peer->maxms) {
14423          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
14424          res = 1;
14425       } else if (peer->lastms) {
14426          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
14427          res = 1;
14428       } else {
14429          ast_copy_string(status, "UNKNOWN", statuslen);
14430       }
14431    } else { 
14432       ast_copy_string(status, "Unmonitored", statuslen);
14433       /* Checking if port is 0 */
14434       res = -1;
14435    }
14436    return res;
14437 }
14438 
14439 /*! \brief return Yes or No depending on the argument.
14440  * This is used in many places in CLI command, having a function to generate
14441  * this helps maintaining a consistent output (and possibly emitting the
14442  * output in other languages, at some point).
14443  */
14444 static const char *cli_yesno(int x)
14445 {
14446    return x ? "Yes" : "No";
14447 }
14448 
14449 /*! \brief  Show active TCP connections */
14450 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14451 {
14452    struct sip_threadinfo *th;
14453    struct ao2_iterator i;
14454 
14455 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
14456 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
14457 
14458    switch (cmd) {
14459    case CLI_INIT:
14460       e->command = "sip show tcp";
14461       e->usage =
14462          "Usage: sip show tcp\n"
14463          "       Lists all active TCP/TLS sessions.\n";
14464       return NULL;
14465    case CLI_GENERATE:
14466       return NULL;
14467    }
14468 
14469    if (a->argc != 3)
14470       return CLI_SHOWUSAGE;
14471 
14472    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
14473    i = ao2_iterator_init(threadt, 0);
14474    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
14475       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
14476          ntohs(th->tcptls_session->remote_address.sin_port), 
14477          get_transport(th->type), 
14478          (th->tcptls_session->client ? "Client" : "Server"));
14479       ao2_t_ref(th, -1, "decrement ref from iterator");
14480    }
14481    ao2_iterator_destroy(&i);
14482    return CLI_SUCCESS;
14483 #undef FORMAT
14484 #undef FORMAT2
14485 }
14486 
14487 /*! \brief  CLI Command 'SIP Show Users' */
14488 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14489 {
14490    regex_t regexbuf;
14491    int havepattern = FALSE;
14492    struct ao2_iterator user_iter;
14493    struct sip_peer *user;
14494 
14495 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
14496 
14497    switch (cmd) {
14498    case CLI_INIT:
14499       e->command = "sip show users";
14500       e->usage =
14501          "Usage: sip show users [like <pattern>]\n"
14502          "       Lists all known SIP users.\n"
14503          "       Optional regular expression pattern is used to filter the user list.\n";
14504       return NULL;
14505    case CLI_GENERATE:
14506       return NULL;
14507    }
14508 
14509    switch (a->argc) {
14510    case 5:
14511       if (!strcasecmp(a->argv[3], "like")) {
14512          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
14513             return CLI_SHOWUSAGE;
14514          havepattern = TRUE;
14515       } else
14516          return CLI_SHOWUSAGE;
14517    case 3:
14518       break;
14519    default:
14520       return CLI_SHOWUSAGE;
14521    }
14522 
14523    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
14524 
14525    user_iter = ao2_iterator_init(peers, 0);
14526    while ((user = ao2_iterator_next(&user_iter))) {
14527       ao2_lock(user);
14528       if (!(user->type & SIP_TYPE_USER)) {
14529          ao2_unlock(user);
14530          unref_peer(user, "sip show users");
14531          continue;
14532       }
14533 
14534       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
14535          ao2_unlock(user);
14536          unref_peer(user, "sip show users");
14537          continue;
14538       }
14539 
14540       ast_cli(a->fd, FORMAT, user->name, 
14541          user->secret, 
14542          user->accountcode,
14543          user->context,
14544          cli_yesno(user->ha != NULL),
14545          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
14546       ao2_unlock(user);
14547       unref_peer(user, "sip show users");
14548    }
14549    ao2_iterator_destroy(&user_iter);
14550 
14551    if (havepattern)
14552       regfree(&regexbuf);
14553 
14554    return CLI_SUCCESS;
14555 #undef FORMAT
14556 }
14557 
14558 /*! \brief Manager Action SIPShowRegistry description */
14559 static char mandescr_show_registry[] =
14560 "Description: Lists all registration requests and status\n"
14561 "Registrations will follow as separate events. followed by a final event called\n"
14562 "RegistrationsComplete.\n"
14563 "Variables: \n"
14564 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
14565 
14566 /*! \brief Show SIP registrations in the manager API */
14567 static int manager_show_registry(struct mansession *s, const struct message *m)
14568 {
14569    const char *id = astman_get_header(m, "ActionID");
14570    char idtext[256] = "";
14571    int total = 0;
14572 
14573    if (!ast_strlen_zero(id))
14574       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14575 
14576    astman_send_listack(s, m, "Registrations will follow", "start");
14577 
14578    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14579       ASTOBJ_RDLOCK(iterator);
14580       astman_append(s,
14581          "Event: RegistryEntry\r\n"
14582          "%s"
14583          "Host: %s\r\n"
14584          "Port: %d\r\n"
14585          "Username: %s\r\n"
14586          "Refresh: %d\r\n"
14587          "State: %s\r\n"
14588          "RegistrationTime: %ld\r\n"
14589          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
14590                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
14591       ASTOBJ_UNLOCK(iterator);
14592       total++;
14593    } while(0));
14594 
14595    astman_append(s,
14596       "Event: RegistrationsComplete\r\n"
14597       "EventList: Complete\r\n"
14598       "ListItems: %d\r\n"
14599       "%s"
14600       "\r\n", total, idtext);
14601    
14602    return 0;
14603 }
14604 
14605 static char mandescr_show_peers[] = 
14606 "Description: Lists SIP peers in text format with details on current status.\n"
14607 "Peerlist will follow as separate events, followed by a final event called\n"
14608 "PeerlistComplete.\n"
14609 "Variables: \n"
14610 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
14611 
14612 /*! \brief  Show SIP peers in the manager API */
14613 /*    Inspired from chan_iax2 */
14614 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
14615 {
14616    const char *id = astman_get_header(m, "ActionID");
14617    const char *a[] = {"sip", "show", "peers"};
14618    char idtext[256] = "";
14619    int total = 0;
14620 
14621    if (!ast_strlen_zero(id))
14622       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14623 
14624    astman_send_listack(s, m, "Peer status list will follow", "start");
14625    /* List the peers in separate manager events */
14626    _sip_show_peers(-1, &total, s, m, 3, a);
14627    /* Send final confirmation */
14628    astman_append(s,
14629    "Event: PeerlistComplete\r\n"
14630    "EventList: Complete\r\n"
14631    "ListItems: %d\r\n"
14632    "%s"
14633    "\r\n", total, idtext);
14634    return 0;
14635 }
14636 
14637 /*! \brief  CLI Show Peers command */
14638 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14639 {
14640    switch (cmd) {
14641    case CLI_INIT:
14642       e->command = "sip show peers";
14643       e->usage =
14644          "Usage: sip show peers [like <pattern>]\n"
14645          "       Lists all known SIP peers.\n"
14646          "       Optional regular expression pattern is used to filter the peer list.\n";
14647       return NULL;
14648    case CLI_GENERATE:
14649       return NULL;
14650    }
14651 
14652    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
14653 }
14654 
14655 int peercomparefunc(const void *a, const void *b);
14656 
14657 int peercomparefunc(const void *a, const void *b)
14658 {
14659    struct sip_peer **ap = (struct sip_peer **)a;
14660    struct sip_peer **bp = (struct sip_peer **)b;
14661    return strcmp((*ap)->name, (*bp)->name);
14662 }
14663 
14664 
14665 /*! \brief Execute sip show peers command */
14666 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
14667 {
14668    regex_t regexbuf;
14669    int havepattern = FALSE;
14670    struct sip_peer *peer;
14671    struct ao2_iterator i;
14672    
14673 /* the last argument is left-aligned, so we don't need a size anyways */
14674 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
14675 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
14676 
14677    char name[256];
14678    int total_peers = 0;
14679    int peers_mon_online = 0;
14680    int peers_mon_offline = 0;
14681    int peers_unmon_offline = 0;
14682    int peers_unmon_online = 0;
14683    const char *id;
14684    char idtext[256] = "";
14685    int realtimepeers;
14686    int objcount = ao2_container_count(peers);
14687    struct sip_peer **peerarray;
14688    int k;
14689    
14690    
14691    realtimepeers = ast_check_realtime("sippeers");
14692    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
14693 
14694    if (s) { /* Manager - get ActionID */
14695       id = astman_get_header(m, "ActionID");
14696       if (!ast_strlen_zero(id))
14697          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
14698    }
14699 
14700    switch (argc) {
14701    case 5:
14702       if (!strcasecmp(argv[3], "like")) {
14703          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
14704             return CLI_SHOWUSAGE;
14705          havepattern = TRUE;
14706       } else
14707          return CLI_SHOWUSAGE;
14708    case 3:
14709       break;
14710    default:
14711       return CLI_SHOWUSAGE;
14712    }
14713 
14714    if (!s) /* Normal list */
14715       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
14716    
14717 
14718    i = ao2_iterator_init(peers, 0);
14719    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
14720       ao2_lock(peer);
14721 
14722       if (!(peer->type & SIP_TYPE_PEER)) {
14723          ao2_unlock(peer);
14724          unref_peer(peer, "unref peer because it's actually a user");
14725          continue;
14726       }
14727 
14728       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14729          objcount--;
14730          ao2_unlock(peer);
14731          unref_peer(peer, "toss iterator peer ptr before continue");
14732          continue;
14733       }
14734 
14735       peerarray[total_peers++] = peer;
14736       ao2_unlock(peer);
14737    }
14738    ao2_iterator_destroy(&i);
14739    
14740    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
14741 
14742    for(k=0; k < total_peers; k++) {
14743       char status[20] = "";
14744       char srch[2000];
14745       char pstatus;
14746       peer = peerarray[k];
14747       
14748       ao2_lock(peer);
14749       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
14750          ao2_unlock(peer);
14751          unref_peer(peer, "toss iterator peer ptr before continue");
14752          continue;
14753       }
14754 
14755       if (!ast_strlen_zero(peer->username) && !s)
14756          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
14757       else
14758          ast_copy_string(name, peer->name, sizeof(name));
14759       
14760       pstatus = peer_status(peer, status, sizeof(status));
14761       if (pstatus == 1)
14762          peers_mon_online++;
14763       else if (pstatus == 0)
14764          peers_mon_offline++;
14765       else {
14766          if (peer->addr.sin_port == 0)
14767             peers_unmon_offline++;
14768          else
14769             peers_unmon_online++;
14770       }
14771 
14772       snprintf(srch, sizeof(srch), FORMAT, name,
14773          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14774          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14775          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14776          peer->ha ? " A " : "   ",  /* permit/deny */
14777          ntohs(peer->addr.sin_port), status,
14778          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14779 
14780       if (!s)  {/* Normal CLI list */
14781          ast_cli(fd, FORMAT, name, 
14782          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
14783          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
14784          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
14785          peer->ha ? " A " : "   ",       /* permit/deny */
14786          
14787          ntohs(peer->addr.sin_port), status,
14788          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
14789       } else { /* Manager format */
14790          /* The names here need to be the same as other channels */
14791          astman_append(s, 
14792          "Event: PeerEntry\r\n%s"
14793          "Channeltype: SIP\r\n"
14794          "ObjectName: %s\r\n"
14795          "ChanObjectType: peer\r\n" /* "peer" or "user" */
14796          "IPaddress: %s\r\n"
14797          "IPport: %d\r\n"
14798          "Dynamic: %s\r\n"
14799          "Natsupport: %s\r\n"
14800          "VideoSupport: %s\r\n"
14801          "TextSupport: %s\r\n"
14802          "ACL: %s\r\n"
14803          "Status: %s\r\n"
14804          "RealtimeDevice: %s\r\n\r\n", 
14805          idtext,
14806          peer->name, 
14807          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
14808          ntohs(peer->addr.sin_port), 
14809          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
14810          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
14811          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
14812          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
14813          peer->ha ? "yes" : "no",       /* permit/deny */
14814          status,
14815          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14816       }
14817       ao2_unlock(peer);
14818       unref_peer(peer, "toss iterator peer ptr");
14819    }
14820    
14821    if (!s)
14822       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14823               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14824 
14825    if (havepattern)
14826       regfree(&regexbuf);
14827 
14828    if (total)
14829       *total = total_peers;
14830    
14831    ast_free(peerarray);
14832    
14833    return CLI_SUCCESS;
14834 #undef FORMAT
14835 #undef FORMAT2
14836 }
14837 
14838 static int peer_dump_func(void *userobj, void *arg, int flags)
14839 {
14840    struct sip_peer *peer = userobj;
14841    int refc = ao2_t_ref(userobj, 0, "");
14842    int *fd = arg;
14843    
14844    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
14845           peer->name, 0, refc);
14846    return 0;
14847 }
14848 
14849 static int dialog_dump_func(void *userobj, void *arg, int flags)
14850 {
14851    struct sip_pvt *pvt = userobj;
14852    int refc = ao2_t_ref(userobj, 0, "");
14853    int *fd = arg;
14854    
14855    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
14856           pvt->callid, 0, refc);
14857    return 0;
14858 }
14859 
14860 
14861 /*! \brief List all allocated SIP Objects (realtime or static) */
14862 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14863 {
14864    char tmp[256];
14865    
14866    switch (cmd) {
14867    case CLI_INIT:
14868       e->command = "sip show objects";
14869       e->usage =
14870          "Usage: sip show objects\n"
14871          "       Lists status of known SIP objects\n";
14872       return NULL;
14873    case CLI_GENERATE:
14874       return NULL;
14875    }  
14876 
14877    if (a->argc != 3)
14878       return CLI_SHOWUSAGE;
14879    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14880    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14881    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14882    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
14883    ast_cli(a->fd, "-= Dialog objects:\n\n");
14884    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14885    return CLI_SUCCESS;
14886 }
14887 /*! \brief Print call group and pickup group */
14888 static void  print_group(int fd, ast_group_t group, int crlf)
14889 {
14890    char buf[256];
14891    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14892 }
14893 
14894 /*! \brief mapping between dtmf flags and strings */
14895 static struct _map_x_s dtmfstr[] = {
14896    { SIP_DTMF_RFC2833,     "rfc2833" },
14897    { SIP_DTMF_INFO,        "info" },
14898    { SIP_DTMF_SHORTINFO,   "shortinfo" },
14899    { SIP_DTMF_INBAND,      "inband" },
14900    { SIP_DTMF_AUTO,        "auto" },
14901    { -1,                   NULL }, /* terminator */
14902 };
14903 
14904 /*! \brief Convert DTMF mode to printable string */
14905 static const char *dtmfmode2str(int mode)
14906 {
14907    return map_x_s(dtmfstr, mode, "<error>");
14908 }
14909 
14910 /*! \brief maps a string to dtmfmode, returns -1 on error */
14911 static int str2dtmfmode(const char *str)
14912 {
14913    return map_s_x(dtmfstr, str, -1);
14914 }
14915 
14916 static struct _map_x_s insecurestr[] = {
14917    { SIP_INSECURE_PORT,    "port" },
14918    { SIP_INSECURE_INVITE,  "invite" },
14919    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
14920    { 0,                    "no" },
14921    { -1,                   NULL }, /* terminator */
14922 };
14923 
14924 /*! \brief Convert Insecure setting to printable string */
14925 static const char *insecure2str(int mode)
14926 {
14927    return map_x_s(insecurestr, mode, "<error>");
14928 }
14929 
14930 /*! \brief Destroy disused contexts between reloads
14931    Only used in reload_config so the code for regcontext doesn't get ugly
14932 */
14933 static void cleanup_stale_contexts(char *new, char *old)
14934 {
14935    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
14936 
14937    while ((oldcontext = strsep(&old, "&"))) {
14938       stalecontext = '\0';
14939       ast_copy_string(newlist, new, sizeof(newlist));
14940       stringp = newlist;
14941       while ((newcontext = strsep(&stringp, "&"))) {
14942          if (!strcmp(newcontext, oldcontext)) {
14943             /* This is not the context you're looking for */
14944             stalecontext = '\0';
14945             break;
14946          } else if (strcmp(newcontext, oldcontext)) {
14947             stalecontext = oldcontext;
14948          }
14949          
14950       }
14951       if (stalecontext)
14952          ast_context_destroy(ast_context_find(stalecontext), "SIP");
14953    }
14954 }
14955 
14956 /*! 
14957  * \brief Match dialogs that need to be destroyed
14958  *
14959  * \details This is used with ao2_callback to unlink/delete all dialogs that
14960  * are marked needdestroy. It will return CMP_MATCH for candidates, and they
14961  * will be unlinked.
14962  *
14963  * \todo Re-work this to improve efficiency.  Currently, this function is called
14964  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
14965  * potentially even more often when the scheduler has entries to run.
14966  */
14967 
14968 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
14969 {
14970    struct sip_pvt *dialog = dialogobj;
14971    time_t *t = arg;
14972 
14973    if (sip_pvt_trylock(dialog)) {
14974       /* Don't block the monitor thread.  This function is called often enough
14975        * that we can wait for the next time around. */
14976       return 0;
14977    }
14978    
14979    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14980    check_rtp_timeout(dialog, *t);
14981 
14982    /* If we have sessions that needs to be destroyed, do it now */
14983    /* Check if we have outstanding requests not responsed to or an active call
14984       - if that's the case, wait with destruction */
14985    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
14986       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
14987       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
14988          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14989          sip_pvt_unlock(dialog);
14990          return 0;
14991       }
14992       
14993       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
14994          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14995          sip_pvt_unlock(dialog);
14996          return 0;
14997       }
14998 
14999       sip_pvt_unlock(dialog);
15000       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
15001       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
15002       dialog_unlink_all(dialog, TRUE, FALSE);
15003       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
15004    }
15005 
15006    sip_pvt_unlock(dialog);
15007 
15008    return 0;
15009 }
15010 
15011 /* this func is used with ao2_callback to unlink/delete all marked
15012    peers */
15013 static int peer_is_marked(void *peerobj, void *arg, int flags)
15014 {
15015    struct sip_peer *peer = peerobj;
15016    return peer->the_mark ? CMP_MATCH : 0;
15017 }
15018 
15019 /*! \brief Remove temporary realtime objects from memory (CLI) */
15020 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
15021 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15022 {
15023    struct sip_peer *peer, *pi;
15024    int prunepeer = FALSE;
15025    int multi = FALSE;
15026    char *name = NULL;
15027    regex_t regexbuf;
15028    struct ao2_iterator i;
15029    static char *choices[] = { "all", "like", NULL };
15030    char *cmplt;
15031    
15032    if (cmd == CLI_INIT) {
15033       e->command = "sip prune realtime [peer|all]";
15034       e->usage =
15035          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
15036          "       Prunes object(s) from the cache.\n"
15037          "       Optional regular expression pattern is used to filter the objects.\n";
15038       return NULL;
15039    } else if (cmd == CLI_GENERATE) {
15040       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
15041          cmplt = ast_cli_complete(a->word, choices, a->n);
15042          if (!cmplt)
15043             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
15044          return cmplt;
15045       }
15046       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
15047          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
15048       return NULL;
15049    }
15050    switch (a->argc) {
15051    case 4:
15052       name = a->argv[3];
15053       /* we accept a name in position 3, but keywords are not good. */
15054       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
15055          return CLI_SHOWUSAGE;
15056       prunepeer = TRUE;
15057       if (!strcasecmp(name, "all")) {
15058          multi = TRUE;
15059          name = NULL;
15060       }
15061       /* else a single name, already set */
15062       break;
15063    case 5:
15064       /* sip prune realtime {peer|like} name */
15065       name = a->argv[4];
15066       if (!strcasecmp(a->argv[3], "peer"))
15067          prunepeer = TRUE;
15068       else if (!strcasecmp(a->argv[3], "like")) {
15069          prunepeer = TRUE;
15070          multi = TRUE;
15071       } else
15072          return CLI_SHOWUSAGE;
15073       if (!strcasecmp(name, "like"))
15074          return CLI_SHOWUSAGE;
15075       if (!multi && !strcasecmp(name, "all")) {
15076          multi = TRUE;
15077          name = NULL;
15078       }
15079       break;
15080    case 6:
15081       name = a->argv[5];
15082       multi = TRUE;
15083       /* sip prune realtime {peer} like name */
15084       if (strcasecmp(a->argv[4], "like"))
15085          return CLI_SHOWUSAGE;
15086       if (!strcasecmp(a->argv[3], "peer")) {
15087          prunepeer = TRUE;
15088       } else
15089          return CLI_SHOWUSAGE;
15090       break;
15091    default:
15092       return CLI_SHOWUSAGE;
15093    }
15094 
15095    if (multi && name) {
15096       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
15097          return CLI_SHOWUSAGE;
15098    }
15099 
15100    if (multi) {
15101       if (prunepeer) {
15102          int pruned = 0;
15103          
15104          i = ao2_iterator_init(peers, 0);
15105          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15106             ao2_lock(pi);
15107             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
15108                unref_peer(pi, "toss iterator peer ptr before continue");
15109                ao2_unlock(pi);
15110                continue;
15111             };
15112             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15113                pi->the_mark = 1;
15114                pruned++;
15115             }
15116             ao2_unlock(pi);
15117             unref_peer(pi, "toss iterator peer ptr");
15118          }
15119          ao2_iterator_destroy(&i);
15120          if (pruned) {
15121             ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
15122                   "initiating callback to remove marked peers");
15123             ast_cli(a->fd, "%d peers pruned.\n", pruned);
15124          } else
15125             ast_cli(a->fd, "No peers found to prune.\n");
15126       }
15127    } else {
15128       if (prunepeer) {
15129          struct sip_peer tmp;
15130          ast_copy_string(tmp.name, name, sizeof(tmp.name));
15131          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
15132             if (peer->addr.sin_addr.s_addr) {
15133                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
15134             }
15135             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
15136                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
15137                /* put it back! */
15138                ao2_t_link(peers, peer, "link peer into peer table");
15139                if (peer->addr.sin_addr.s_addr) {
15140                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
15141                }
15142                
15143             } else
15144                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
15145             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
15146          } else
15147             ast_cli(a->fd, "Peer '%s' not found.\n", name);
15148       }
15149    }
15150 
15151    return CLI_SUCCESS;
15152 }
15153 
15154 /*! \brief Print codec list from preference to CLI/manager */
15155 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
15156 {
15157    int x, codec;
15158 
15159    for(x = 0; x < 32 ; x++) {
15160       codec = ast_codec_pref_index(pref, x);
15161       if (!codec)
15162          break;
15163       ast_cli(fd, "%s", ast_getformatname(codec));
15164       ast_cli(fd, ":%d", pref->framing[x]);
15165       if (x < 31 && ast_codec_pref_index(pref, x + 1))
15166          ast_cli(fd, ",");
15167    }
15168    if (!x)
15169       ast_cli(fd, "none");
15170 }
15171 
15172 /*! \brief Print domain mode to cli */
15173 static const char *domain_mode_to_text(const enum domain_mode mode)
15174 {
15175    switch (mode) {
15176    case SIP_DOMAIN_AUTO:
15177       return "[Automatic]";
15178    case SIP_DOMAIN_CONFIG:
15179       return "[Configured]";
15180    }
15181 
15182    return "";
15183 }
15184 
15185 /*! \brief CLI command to list local domains */
15186 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15187 {
15188    struct domain *d;
15189 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
15190 
15191    switch (cmd) {
15192    case CLI_INIT:
15193       e->command = "sip show domains";
15194       e->usage =
15195          "Usage: sip show domains\n"
15196          "       Lists all configured SIP local domains.\n"
15197          "       Asterisk only responds to SIP messages to local domains.\n";
15198       return NULL;
15199    case CLI_GENERATE:
15200       return NULL;
15201    }
15202 
15203    if (AST_LIST_EMPTY(&domain_list)) {
15204       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
15205       return CLI_SUCCESS;
15206    } else {
15207       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
15208       AST_LIST_LOCK(&domain_list);
15209       AST_LIST_TRAVERSE(&domain_list, d, list)
15210          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
15211             domain_mode_to_text(d->mode));
15212       AST_LIST_UNLOCK(&domain_list);
15213       ast_cli(a->fd, "\n");
15214       return CLI_SUCCESS;
15215    }
15216 }
15217 #undef FORMAT
15218 
15219 static char mandescr_show_peer[] = 
15220 "Description: Show one SIP peer with details on current status.\n"
15221 "Variables: \n"
15222 "  Peer: <name>           The peer name you want to check.\n"
15223 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
15224 
15225 /*! \brief Show SIP peers in the manager API  */
15226 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
15227 {
15228    const char *a[4];
15229    const char *peer;
15230 
15231    peer = astman_get_header(m, "Peer");
15232    if (ast_strlen_zero(peer)) {
15233       astman_send_error(s, m, "Peer: <name> missing.");
15234       return 0;
15235    }
15236    a[0] = "sip";
15237    a[1] = "show";
15238    a[2] = "peer";
15239    a[3] = peer;
15240 
15241    _sip_show_peer(1, -1, s, m, 4, a);
15242    astman_append(s, "\r\n\r\n" );
15243    return 0;
15244 }
15245 
15246 /*! \brief Show one peer in detail */
15247 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15248 {
15249    switch (cmd) {
15250    case CLI_INIT:
15251       e->command = "sip show peer";
15252       e->usage =
15253          "Usage: sip show peer <name> [load]\n"
15254          "       Shows all details on one SIP peer and the current status.\n"
15255          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15256       return NULL;
15257    case CLI_GENERATE:
15258       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15259    }
15260    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15261 }
15262 
15263 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
15264 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15265 {
15266    struct sip_peer *peer;
15267    int load_realtime;
15268 
15269    if (argc < 4)
15270       return CLI_SHOWUSAGE;
15271 
15272    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15273    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
15274       sip_poke_peer(peer, 1);
15275       unref_peer(peer, "qualify: done with peer");
15276    } else if (type == 0) {
15277       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
15278    } else {
15279       astman_send_error(s, m, "Peer not found");
15280    }
15281    return CLI_SUCCESS;
15282 }
15283 
15284 /*! \brief Qualify SIP peers in the manager API  */
15285 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
15286 {
15287    const char *a[4];
15288    const char *peer;
15289 
15290    peer = astman_get_header(m, "Peer");
15291    if (ast_strlen_zero(peer)) {
15292       astman_send_error(s, m, "Peer: <name> missing.");
15293       return 0;
15294    }
15295    a[0] = "sip";
15296    a[1] = "qualify";
15297    a[2] = "peer";
15298    a[3] = peer;
15299 
15300    _sip_qualify_peer(1, -1, s, m, 4, a);
15301    astman_append(s, "\r\n\r\n" );
15302    return 0;
15303 }
15304 
15305 /*! \brief Send an OPTIONS packet to a SIP peer */
15306 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15307 {
15308    switch (cmd) {
15309    case CLI_INIT:
15310       e->command = "sip qualify peer";
15311       e->usage =
15312          "Usage: sip qualify peer <name> [load]\n"
15313          "       Requests a response from one SIP peer and the current status.\n"
15314          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15315       return NULL;
15316    case CLI_GENERATE:
15317       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
15318    }
15319    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
15320 }
15321 
15322 /*! \brief list peer mailboxes to CLI */
15323 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
15324 {
15325    struct sip_mailbox *mailbox;
15326 
15327    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
15328       ast_str_append(mailbox_str, 0, "%s%s%s%s",
15329          mailbox->mailbox,
15330          ast_strlen_zero(mailbox->context) ? "" : "@",
15331          S_OR(mailbox->context, ""),
15332          AST_LIST_NEXT(mailbox, entry) ? "," : "");
15333    }
15334 }
15335 
15336 static struct _map_x_s faxecmodes[] = {
15337    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
15338    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
15339    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
15340    { -1,                NULL},
15341 };
15342 
15343 static const char *faxec2str(int faxec)
15344 {
15345    return map_x_s(faxecmodes, faxec, "Unknown");
15346 }
15347 
15348 /*! \brief Show one peer in detail (main function) */
15349 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
15350 {
15351    char status[30] = "";
15352    char cbuf[256];
15353    struct sip_peer *peer;
15354    char codec_buf[512];
15355    struct ast_codec_pref *pref;
15356    struct ast_variable *v;
15357    struct sip_auth *auth;
15358    int x = 0, codec = 0, load_realtime;
15359    int realtimepeers;
15360 
15361    realtimepeers = ast_check_realtime("sippeers");
15362 
15363    if (argc < 4)
15364       return CLI_SHOWUSAGE;
15365 
15366    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
15367    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
15368 
15369    if (s) {    /* Manager */
15370       if (peer) {
15371          const char *id = astman_get_header(m, "ActionID");
15372 
15373          astman_append(s, "Response: Success\r\n");
15374          if (!ast_strlen_zero(id))
15375             astman_append(s, "ActionID: %s\r\n", id);
15376       } else {
15377          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
15378          astman_send_error(s, m, cbuf);
15379          return CLI_SUCCESS;
15380       }
15381    }
15382    if (peer && type==0 ) { /* Normal listing */
15383       struct ast_str *mailbox_str = ast_str_alloca(512);
15384       ast_cli(fd, "\n\n");
15385       ast_cli(fd, "  * Name       : %s\n", peer->name);
15386       if (realtimepeers) { /* Realtime is enabled */
15387          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
15388       }
15389       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
15390       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
15391       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
15392       for (auth = peer->auth; auth; auth = auth->next) {
15393          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
15394          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
15395       }
15396       ast_cli(fd, "  Context      : %s\n", peer->context);
15397       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
15398       ast_cli(fd, "  Language     : %s\n", peer->language);
15399       if (!ast_strlen_zero(peer->accountcode))
15400          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
15401       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
15402       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
15403       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
15404       if (!ast_strlen_zero(peer->fromuser))
15405          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
15406       if (!ast_strlen_zero(peer->fromdomain))
15407          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
15408       ast_cli(fd, "  Callgroup    : ");
15409       print_group(fd, peer->callgroup, 0);
15410       ast_cli(fd, "  Pickupgroup  : ");
15411       print_group(fd, peer->pickupgroup, 0);
15412       peer_mailboxes_to_str(&mailbox_str, peer);
15413       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
15414       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
15415       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
15416       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
15417       if (peer->busy_level)
15418          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
15419       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
15420       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
15421       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
15422       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
15423       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15424       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15425       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
15426       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15427       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15428       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
15429       ast_cli(fd, "  DirectMedia  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
15430       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
15431       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
15432       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15433       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
15434       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15435       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
15436       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
15437       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15438       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15439       if (peer->outboundproxy)
15440          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
15441                      peer->outboundproxy->force ? "(forced)" : "");
15442 
15443       /* - is enumerated */
15444       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15445       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
15446       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
15447       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
15448       ast_cli(fd, "  Addr->IP     : %s Port %d\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
15449       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15450       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
15451       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports)); 
15452       if (!ast_strlen_zero(global_regcontext))
15453          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
15454       ast_cli(fd, "  Def. Username: %s\n", peer->username);
15455       ast_cli(fd, "  SIP Options  : ");
15456       if (peer->sipoptions) {
15457          int lastoption = -1;
15458          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15459             if (sip_options[x].id != lastoption) {
15460                if (peer->sipoptions & sip_options[x].id)
15461                   ast_cli(fd, "%s ", sip_options[x].text);
15462                lastoption = x;
15463             }
15464          }
15465       } else
15466          ast_cli(fd, "(none)");
15467 
15468       ast_cli(fd, "\n");
15469       ast_cli(fd, "  Codecs       : ");
15470       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15471       ast_cli(fd, "%s\n", codec_buf);
15472       ast_cli(fd, "  Codec Order  : (");
15473       print_codec_to_cli(fd, &peer->prefs);
15474       ast_cli(fd, ")\n");
15475 
15476       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
15477       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
15478       ast_cli(fd, "  Status       : ");
15479       peer_status(peer, status, sizeof(status));
15480       ast_cli(fd, "%s\n", status);
15481       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
15482       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
15483       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
15484       if (peer->chanvars) {
15485          ast_cli(fd, "  Variables    :\n");
15486          for (v = peer->chanvars ; v ; v = v->next)
15487             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
15488       }
15489 
15490       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
15491       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
15492       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
15493       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
15494       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
15495       ast_cli(fd, "\n");
15496       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
15497    } else  if (peer && type == 1) { /* manager listing */
15498       char buffer[256];
15499       struct ast_str *mailbox_str = ast_str_alloca(512);
15500       astman_append(s, "Channeltype: SIP\r\n");
15501       astman_append(s, "ObjectName: %s\r\n", peer->name);
15502       astman_append(s, "ChanObjectType: peer\r\n");
15503       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
15504       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
15505       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
15506       astman_append(s, "Context: %s\r\n", peer->context);
15507       astman_append(s, "Language: %s\r\n", peer->language);
15508       if (!ast_strlen_zero(peer->accountcode))
15509          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
15510       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
15511       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
15512       if (!ast_strlen_zero(peer->fromuser))
15513          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
15514       if (!ast_strlen_zero(peer->fromdomain))
15515          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
15516       astman_append(s, "Callgroup: ");
15517       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
15518       astman_append(s, "Pickupgroup: ");
15519       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
15520       peer_mailboxes_to_str(&mailbox_str, peer);
15521       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
15522       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
15523       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
15524       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
15525       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
15526       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
15527       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
15528       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
15529       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
15530       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
15531       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
15532       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
15533       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15534       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
15535       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
15536       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
15537       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
15538       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
15539       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
15540       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
15541       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
15542       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
15543       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
15544       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
15545       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
15546 
15547       /* - is enumerated */
15548       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
15549       astman_append(s, "ToHost: %s\r\n", peer->tohost);
15550       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n",  peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", ntohs(peer->addr.sin_port));
15551       astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
15552       astman_append(s, "Default-Username: %s\r\n", peer->username);
15553       if (!ast_strlen_zero(global_regcontext))
15554          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
15555       astman_append(s, "Codecs: ");
15556       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
15557       astman_append(s, "%s\r\n", codec_buf);
15558       astman_append(s, "CodecOrder: ");
15559       pref = &peer->prefs;
15560       for(x = 0; x < 32 ; x++) {
15561          codec = ast_codec_pref_index(pref, x);
15562          if (!codec)
15563             break;
15564          astman_append(s, "%s", ast_getformatname(codec));
15565          if (x < 31 && ast_codec_pref_index(pref, x+1))
15566             astman_append(s, ",");
15567       }
15568 
15569       astman_append(s, "\r\n");
15570       astman_append(s, "Status: ");
15571       peer_status(peer, status, sizeof(status));
15572       astman_append(s, "%s\r\n", status);
15573       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
15574       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
15575       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
15576       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
15577       if (peer->chanvars) {
15578          for (v = peer->chanvars ; v ; v = v->next) {
15579             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
15580          }
15581       }
15582 
15583       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
15584 
15585    } else {
15586       ast_cli(fd, "Peer %s not found.\n", argv[3]);
15587       ast_cli(fd, "\n");
15588    }
15589 
15590    return CLI_SUCCESS;
15591 }
15592 
15593 /*! \brief Do completion on user name */
15594 static char *complete_sip_user(const char *word, int state)
15595 {
15596    char *result = NULL;
15597    int wordlen = strlen(word);
15598    int which = 0;
15599    struct ao2_iterator user_iter;
15600    struct sip_peer *user;
15601 
15602    user_iter = ao2_iterator_init(peers, 0);
15603    while ((user = ao2_iterator_next(&user_iter))) {
15604       ao2_lock(user);
15605       if (!(user->type & SIP_TYPE_USER)) {
15606          ao2_unlock(user);
15607          unref_peer(user, "complete sip user");
15608          continue;
15609       }
15610       /* locking of the object is not required because only the name and flags are being compared */
15611       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
15612          result = ast_strdup(user->name);
15613       }
15614       ao2_unlock(user);
15615       unref_peer(user, "complete sip user");
15616    }
15617    ao2_iterator_destroy(&user_iter);
15618    return result;
15619 }
15620 /*! \brief Support routine for 'sip show user' CLI */
15621 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
15622 {
15623    if (pos == 3)
15624       return complete_sip_user(word, state);
15625 
15626    return NULL;
15627 }
15628 
15629 /*! \brief Show one user in detail */
15630 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15631 {
15632    char cbuf[256];
15633    struct sip_peer *user;
15634    struct ast_variable *v;
15635    int load_realtime;
15636 
15637    switch (cmd) {
15638    case CLI_INIT:
15639       e->command = "sip show user";
15640       e->usage =
15641          "Usage: sip show user <name> [load]\n"
15642          "       Shows all details on one SIP user and the current status.\n"
15643          "       Option \"load\" forces lookup of peer in realtime storage.\n";
15644       return NULL;
15645    case CLI_GENERATE:
15646       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
15647    }
15648 
15649    if (a->argc < 4)
15650       return CLI_SHOWUSAGE;
15651 
15652    /* Load from realtime storage? */
15653    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
15654 
15655    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
15656       ao2_lock(user);
15657       ast_cli(a->fd, "\n\n");
15658       ast_cli(a->fd, "  * Name       : %s\n", user->name);
15659       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
15660       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
15661       ast_cli(a->fd, "  Context      : %s\n", user->context);
15662       ast_cli(a->fd, "  Language     : %s\n", user->language);
15663       if (!ast_strlen_zero(user->accountcode))
15664          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
15665       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
15666       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
15667       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
15668       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
15669       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
15670       ast_cli(a->fd, "  Callgroup    : ");
15671       print_group(a->fd, user->callgroup, 0);
15672       ast_cli(a->fd, "  Pickupgroup  : ");
15673       print_group(a->fd, user->pickupgroup, 0);
15674       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
15675       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
15676       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
15677       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
15678       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
15679       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
15680 
15681       ast_cli(a->fd, "  Codec Order  : (");
15682       print_codec_to_cli(a->fd, &user->prefs);
15683       ast_cli(a->fd, ")\n");
15684 
15685       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
15686       if (user->chanvars) {
15687          ast_cli(a->fd, "  Variables    :\n");
15688          for (v = user->chanvars ; v ; v = v->next)
15689             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
15690       }
15691 
15692       ast_cli(a->fd, "\n");
15693 
15694       ao2_unlock(user);
15695       unref_peer(user, "sip show user");
15696    } else {
15697       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
15698       ast_cli(a->fd, "\n");
15699    }
15700 
15701    return CLI_SUCCESS;
15702 }
15703 
15704 
15705 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15706 {
15707    struct ast_str *cbuf;
15708    struct ast_cb_names cbnames = {9, { "retrans_pkt",
15709                                         "__sip_autodestruct",
15710                                         "expire_register",
15711                                         "auto_congest",
15712                                         "sip_reg_timeout",
15713                                         "sip_poke_peer_s",
15714                                         "sip_poke_noanswer",
15715                                         "sip_reregister",
15716                                         "sip_reinvite_retry"},
15717                            { retrans_pkt,
15718                                      __sip_autodestruct,
15719                                      expire_register,
15720                                      auto_congest,
15721                                      sip_reg_timeout,
15722                                      sip_poke_peer_s,
15723                                      sip_poke_noanswer,
15724                                      sip_reregister,
15725                                      sip_reinvite_retry}};
15726    
15727    switch (cmd) {
15728    case CLI_INIT:
15729       e->command = "sip show sched";
15730       e->usage =
15731          "Usage: sip show sched\n"
15732          "       Shows stats on what's in the sched queue at the moment\n";
15733       return NULL;
15734    case CLI_GENERATE:
15735       return NULL;
15736    }
15737 
15738    cbuf = ast_str_alloca(2048);
15739 
15740    ast_cli(a->fd, "\n");
15741    ast_sched_report(sched, &cbuf, &cbnames);
15742    ast_cli(a->fd, "%s", cbuf->str);
15743 
15744    return CLI_SUCCESS;
15745 }
15746 
15747 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
15748 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15749 {
15750 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
15751 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
15752    char host[80];
15753    char tmpdat[256];
15754    struct ast_tm tm;
15755    int counter = 0;
15756 
15757    switch (cmd) {
15758    case CLI_INIT:
15759       e->command = "sip show registry";
15760       e->usage =
15761          "Usage: sip show registry\n"
15762          "       Lists all registration requests and status.\n";
15763       return NULL;
15764    case CLI_GENERATE:
15765       return NULL;
15766    }
15767 
15768    if (a->argc != 3)
15769       return CLI_SHOWUSAGE;
15770    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
15771    
15772    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
15773       ASTOBJ_RDLOCK(iterator);
15774       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
15775       if (iterator->regtime.tv_sec) {
15776          ast_localtime(&iterator->regtime, &tm, NULL);
15777          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
15778       } else 
15779          tmpdat[0] = '\0';
15780       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
15781       ASTOBJ_UNLOCK(iterator);
15782       counter++;
15783    } while(0));
15784    ast_cli(a->fd, "%d SIP registrations.\n", counter);
15785    return CLI_SUCCESS;
15786 #undef FORMAT
15787 #undef FORMAT2
15788 }
15789 
15790 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
15791    \note This function does not tell the SIP device what's going on,
15792    so use it with great care.
15793 */
15794 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15795 {
15796    struct sip_peer *peer;
15797    int load_realtime = 0;
15798 
15799    switch (cmd) {
15800    case CLI_INIT:
15801       e->command = "sip unregister";
15802       e->usage =
15803          "Usage: sip unregister <peer>\n"
15804          "       Unregister (force expiration) a SIP peer from the registry\n";
15805       return NULL;
15806    case CLI_GENERATE:
15807       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15808    }
15809    
15810    if (a->argc != 3)
15811       return CLI_SHOWUSAGE;
15812    
15813    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15814       if (peer->expire > 0) {
15815          AST_SCHED_DEL_UNREF(sched, peer->expire,
15816             unref_peer(peer, "remove register expire ref"));
15817          expire_register(ref_peer(peer, "ref for expire_register"));
15818          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15819       } else {
15820          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15821       }
15822       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15823    } else {
15824       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15825    }
15826    
15827    return CLI_SUCCESS;
15828 }
15829 
15830 /*! \brief Callback for show_chanstats */
15831 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15832 {
15833 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
15834 #define FORMAT  "%-15.15s  %-11.11s  %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.6u\n"
15835    struct sip_pvt *cur = __cur;
15836    unsigned int rxcount, txcount, rxploss, txploss;
15837    char durbuf[10];
15838         int duration;
15839         int durh, durm, durs;
15840    struct ast_channel *c = cur->owner;
15841    struct __show_chan_arg *arg = __arg;
15842    int fd = arg->fd;
15843 
15844 
15845    if (cur->subscribed != NONE) /* Subscriptions */
15846       return 0;   /* don't care, we scan all channels */
15847 
15848    if (!cur->rtp) {
15849       if (sipdebug)
15850          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n", ast_inet_ntoa(cur->sa.sin_addr), cur->callid, invitestate2string[cur->invitestate].desc, "-- No RTP active");
15851       return 0;   /* don't care, we scan all channels */
15852    }
15853    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15854    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15855    rxploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS);
15856    txploss = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS);
15857 
15858    /* Find the duration of this channel */
15859    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15860       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15861       durh = duration / 3600;
15862       durm = (duration % 3600) / 60;
15863       durs = duration % 60;
15864       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15865    } else {
15866       durbuf[0] = '\0';
15867    }
15868    /* Print stats for every call with RTP */
15869    ast_cli(fd, FORMAT, 
15870       ast_inet_ntoa(cur->sa.sin_addr), 
15871       cur->callid, 
15872       durbuf,
15873       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15874       rxcount > (unsigned int) 100000 ? "K":" ",
15875       rxploss,
15876       (rxcount + rxploss) > 0 ? (double) rxploss / (rxcount + rxploss) * 100 : 0,
15877       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15878       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15879       txcount > (unsigned int) 100000 ? "K":" ",
15880       txploss,
15881       txcount > 0 ? (double) txploss / txcount * 100 : 0,
15882       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15883    );
15884    arg->numchans++;
15885 
15886    return 0;   /* don't care, we scan all channels */
15887 }
15888 
15889 /*! \brief SIP show channelstats CLI (main function) */
15890 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15891 {
15892    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15893 
15894    switch (cmd) {
15895    case CLI_INIT:
15896       e->command = "sip show channelstats";
15897       e->usage =
15898          "Usage: sip show channelstats\n"
15899          "       Lists all currently active SIP channel's RTCP statistics.\n"
15900          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15901       return NULL;
15902    case CLI_GENERATE:
15903       return NULL;
15904    }
15905 
15906    if (a->argc != 3)
15907       return CLI_SHOWUSAGE;
15908 
15909    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
15910    /* iterate on the container and invoke the callback on each item */
15911    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
15912    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
15913    return CLI_SUCCESS;
15914 }
15915 #undef FORMAT
15916 #undef FORMAT2
15917 
15918 /*! \brief List global settings for the SIP channel */
15919 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15920 {
15921    int realtimepeers;
15922    int realtimeregs;
15923    char codec_buf[SIPBUFSIZE];
15924    const char *msg;  /* temporary msg pointer */
15925 
15926    switch (cmd) {
15927    case CLI_INIT:
15928       e->command = "sip show settings";
15929       e->usage =
15930          "Usage: sip show settings\n"
15931          "       Provides detailed list of the configuration of the SIP channel.\n";
15932       return NULL;
15933    case CLI_GENERATE:
15934       return NULL;
15935    }
15936 
15937 
15938    realtimepeers = ast_check_realtime("sippeers");
15939    realtimeregs = ast_check_realtime("sipregs");
15940 
15941    if (a->argc != 3)
15942       return CLI_SHOWUSAGE;
15943    ast_cli(a->fd, "\n\nGlobal Settings:\n");
15944    ast_cli(a->fd, "----------------\n");
15945    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
15946    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
15947    ast_cli(a->fd, "  TCP SIP Port:           ");
15948    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
15949       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
15950       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
15951    } else {
15952       ast_cli(a->fd, "Disabled\n");
15953    }
15954    ast_cli(a->fd, "  TLS SIP Port:           ");
15955    if (default_tls_cfg.enabled != FALSE) {
15956       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
15957       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
15958    } else {
15959       ast_cli(a->fd, "Disabled\n");
15960    }
15961    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15962    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
15963    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15964    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(sip_cfg.autocreatepeer));
15965    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
15966    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(sip_cfg.allowguest));
15967    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15968    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15969    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
15970    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
15971    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
15972    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
15973    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
15974    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(sip_cfg.allow_external_domains));
15975    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
15976    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(sip_cfg.alwaysauthreject));
15977    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(sip_cfg.directrtpsetup));
15978    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
15979    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
15980    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
15981    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
15982    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(sip_cfg.regextenonqualify));
15983    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
15984    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
15985    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
15986    ast_cli(a->fd, "  Call Events:            %s\n", sip_cfg.callevents ? "On" : "Off");
15987    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
15988 
15989    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15990    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15991    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
15992 
15993    if (!realtimepeers && !realtimeregs)
15994       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
15995    else
15996       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
15997    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
15998    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
15999    ast_cli(a->fd, "---------------------------\n");
16000    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
16001    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
16002    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
16003    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
16004    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
16005    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
16006    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
16007    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
16008    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
16009    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
16010    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
16011    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
16012    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
16013    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
16014 
16015    ast_cli(a->fd, "\nNetwork Settings:\n");
16016    ast_cli(a->fd, "---------------------------\n");
16017    /* determine if/how SIP address can be remapped */
16018    if (localaddr == NULL)
16019       msg = "Disabled, no localnet list";
16020    else if (externip.sin_addr.s_addr == 0)
16021       msg = "Disabled, externip is 0.0.0.0";
16022    else if (stunaddr.sin_addr.s_addr != 0)
16023       msg = "Enabled using STUN";
16024    else if (!ast_strlen_zero(externhost))
16025       msg = "Enabled using externhost";
16026    else
16027       msg = "Enabled using externip";
16028    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
16029    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
16030    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
16031    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
16032    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
16033    {
16034       struct ast_ha *d;
16035       const char *prefix = "Localnet:";
16036       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
16037 
16038       for (d = localaddr; d ; prefix = "", d = d->next) {
16039          ast_cli(a->fd, "  %-24s%s/%s\n",
16040              prefix, ast_inet_ntoa(d->netaddr),
16041              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
16042       }
16043    }
16044    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
16045  
16046    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
16047    ast_cli(a->fd, "---------------------------\n");
16048    ast_cli(a->fd, "  Codecs:                 ");
16049    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
16050    ast_cli(a->fd, "%s\n", codec_buf);
16051    ast_cli(a->fd, "  Codec Order:            ");
16052    print_codec_to_cli(a->fd, &default_prefs);
16053    ast_cli(a->fd, "\n");
16054    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
16055    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
16056    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(sip_cfg.compactheaders));
16057    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
16058    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
16059    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
16060    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
16061    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(sip_cfg.srvlookup));
16062    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(sip_cfg.pedanticsipchecking));
16063    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
16064    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
16065    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
16066    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
16067    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
16068    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(sip_cfg.notifyringing));
16069    if (sip_cfg.notifyringing) {
16070       ast_cli(a->fd, "    Include CID:          %s%s\n",
16071             cli_yesno(sip_cfg.notifycid),
16072             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
16073    }
16074    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(sip_cfg.notifyhold));
16075    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
16076    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
16077    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
16078    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
16079                      sip_cfg.outboundproxy.force ? "(forced)" : "");
16080    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
16081    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
16082    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
16083    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
16084    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
16085    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
16086    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
16087    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
16088 
16089    ast_cli(a->fd, "\nDefault Settings:\n");
16090    ast_cli(a->fd, "-----------------\n");
16091    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports)); 
16092    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
16093    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
16094    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
16095    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
16096    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
16097    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
16098    ast_cli(a->fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NO) ? "No" : "Yes" );
16099    ast_cli(a->fd, "  Language:               %s\n", default_language);
16100    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
16101    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
16102    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
16103 
16104    
16105    if (realtimepeers || realtimeregs) {
16106       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
16107       ast_cli(a->fd, "----------------------\n");
16108       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
16109       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
16110       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
16111       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
16112       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
16113       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
16114       ast_cli(a->fd, "  Auto Clear:             %d\n", sip_cfg.rtautoclear);
16115    }
16116    ast_cli(a->fd, "\n----\n");
16117    return CLI_SUCCESS;
16118 }
16119 
16120 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16121 {
16122 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
16123    char host[80];
16124    
16125    switch (cmd) {
16126    case CLI_INIT:
16127       e->command = "sip show mwi";
16128       e->usage =
16129          "Usage: sip show mwi\n"
16130          "       Provides a list of MWI subscriptions and status.\n";
16131       return NULL;
16132    case CLI_GENERATE:
16133       return NULL;
16134    }
16135    
16136    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
16137    
16138    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
16139       ASTOBJ_RDLOCK(iterator);
16140       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
16141       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, iterator->subscribed ? "Yes" : "No");
16142       ASTOBJ_UNLOCK(iterator);
16143    } while(0));
16144 
16145    return CLI_SUCCESS;
16146 #undef FORMAT
16147 }
16148 
16149 
16150 /*! \brief Show subscription type in string format */
16151 static const char *subscription_type2str(enum subscriptiontype subtype)
16152 {
16153    int i;
16154 
16155    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16156       if (subscription_types[i].type == subtype) {
16157          return subscription_types[i].text;
16158       }
16159    }
16160    return subscription_types[0].text;
16161 }
16162 
16163 /*! \brief Find subscription type in array */
16164 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
16165 {
16166    int i;
16167 
16168    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
16169       if (subscription_types[i].type == subtype) {
16170          return &subscription_types[i];
16171       }
16172    }
16173    return &subscription_types[0];
16174 }
16175 
16176 /*
16177  * We try to structure all functions that loop on data structures as
16178  * a handler for individual entries, and a mainloop that iterates
16179  * on the main data structure. This way, moving the code to containers
16180  * that support iteration through callbacks will be a lot easier.
16181  */
16182 
16183 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
16184 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
16185 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
16186 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
16187 
16188 /*! \brief callback for show channel|subscription */
16189 static int show_channels_cb(void *__cur, void *__arg, int flags)
16190 {
16191    struct sip_pvt *cur = __cur;
16192    struct __show_chan_arg *arg = __arg;
16193    const struct sockaddr_in *dst = sip_real_dst(cur);
16194    
16195    /* XXX indentation preserved to reduce diff. Will be fixed later */
16196    if (cur->subscribed == NONE && !arg->subscriptions) {
16197       /* set if SIP transfer in progress */
16198       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
16199       char formatbuf[SIPBUFSIZE/2];
16200       
16201       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
16202             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
16203             cur->callid, 
16204             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
16205             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
16206             cur->needdestroy ? "(d)" : "",
16207             cur->lastmsg ,
16208             referstatus
16209          );
16210       arg->numchans++;
16211    }
16212    if (cur->subscribed != NONE && arg->subscriptions) {
16213       struct ast_str *mailbox_str = ast_str_alloca(512);
16214       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
16215          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
16216       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
16217             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
16218                cur->callid,
16219             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
16220             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
16221             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
16222             subscription_type2str(cur->subscribed),
16223             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
16224             cur->expiry
16225          );
16226       arg->numchans++;
16227    }
16228    return 0;   /* don't care, we scan all channels */
16229 }
16230 
16231 /*! \brief CLI for show channels or subscriptions.
16232  * This is a new-style CLI handler so a single function contains
16233  * the prototype for the function, the 'generator' to produce multiple
16234  * entries in case it is required, and the actual handler for the command.
16235  */
16236 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16237 {
16238    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
16239 
16240 
16241    if (cmd == CLI_INIT) {
16242       e->command = "sip show {channels|subscriptions}";
16243       e->usage =
16244          "Usage: sip show channels\n"
16245          "       Lists all currently active SIP calls (dialogs).\n"
16246          "Usage: sip show subscriptions\n"
16247          "       Lists active SIP subscriptions.\n";
16248       return NULL;
16249    } else if (cmd == CLI_GENERATE)
16250       return NULL;
16251 
16252    if (a->argc != e->args)
16253       return CLI_SHOWUSAGE;
16254    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
16255    if (!arg.subscriptions)
16256       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
16257    else
16258       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
16259 
16260    /* iterate on the container and invoke the callback on each item */
16261    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
16262    
16263    /* print summary information */
16264    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
16265       (arg.subscriptions ? "subscription" : "dialog"),
16266       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
16267    return CLI_SUCCESS;
16268 #undef FORMAT
16269 #undef FORMAT2
16270 #undef FORMAT3
16271 }
16272 
16273 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
16274  * This is in charge of generating all strings that match a prefix in the
16275  * given position. As many functions of this kind, each invokation has
16276  * O(state) time complexity so be careful in using it.
16277  */
16278 static char *complete_sipch(const char *line, const char *word, int pos, int state)
16279 {
16280    int which=0;
16281    struct sip_pvt *cur;
16282    char *c = NULL;
16283    int wordlen = strlen(word);
16284    struct ao2_iterator i;
16285 
16286    if (pos != 3) {
16287       return NULL;
16288    }
16289 
16290    i = ao2_iterator_init(dialogs, 0);
16291    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16292       sip_pvt_lock(cur);
16293       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
16294          c = ast_strdup(cur->callid);
16295          sip_pvt_unlock(cur);
16296          dialog_unref(cur, "drop ref in iterator loop break");
16297          break;
16298       }
16299       sip_pvt_unlock(cur);
16300       dialog_unref(cur, "drop ref in iterator loop");
16301    }
16302    ao2_iterator_destroy(&i);
16303    return c;
16304 }
16305 
16306 
16307 /*! \brief Do completion on peer name */
16308 static char *complete_sip_peer(const char *word, int state, int flags2)
16309 {
16310    char *result = NULL;
16311    int wordlen = strlen(word);
16312    int which = 0;
16313    struct ao2_iterator i = ao2_iterator_init(peers, 0);
16314    struct sip_peer *peer;
16315 
16316    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16317       /* locking of the object is not required because only the name and flags are being compared */
16318       if (!strncasecmp(word, peer->name, wordlen) &&
16319             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16320             ++which > state)
16321          result = ast_strdup(peer->name);
16322       unref_peer(peer, "toss iterator peer ptr before break");
16323       if (result) {
16324          break;
16325       }
16326    }
16327    ao2_iterator_destroy(&i);
16328    return result;
16329 }
16330 
16331 /*! \brief Do completion on registered peer name */
16332 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
16333 {
16334        char *result = NULL;
16335        int wordlen = strlen(word);
16336        int which = 0;
16337        struct ao2_iterator i;
16338        struct sip_peer *peer;
16339        
16340        i = ao2_iterator_init(peers, 0);
16341        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
16342           if (!strncasecmp(word, peer->name, wordlen) &&
16343          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
16344          ++which > state && peer->expire > 0)
16345              result = ast_strdup(peer->name);
16346           if (result) {
16347              unref_peer(peer, "toss iterator peer ptr before break");
16348              break;
16349           }
16350           unref_peer(peer, "toss iterator peer ptr");
16351        }
16352        ao2_iterator_destroy(&i);
16353        return result;
16354 }
16355 
16356 /*! \brief Support routine for 'sip show history' CLI */
16357 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
16358 {
16359    if (pos == 3)
16360       return complete_sipch(line, word, pos, state);
16361 
16362    return NULL;
16363 }
16364 
16365 /*! \brief Support routine for 'sip show peer' CLI */
16366 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
16367 {
16368    if (pos == 3) {
16369       return complete_sip_peer(word, state, 0);
16370    }
16371 
16372    return NULL;
16373 }
16374 
16375 /*! \brief Support routine for 'sip unregister' CLI */
16376 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
16377 {
16378        if (pos == 2)
16379                return complete_sip_registered_peer(word, state, 0);
16380 
16381        return NULL;
16382 }
16383 
16384 /*! \brief Support routine for 'sip notify' CLI */
16385 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
16386 {
16387    char *c = NULL;
16388 
16389    if (pos == 2) {
16390       int which = 0;
16391       char *cat = NULL;
16392       int wordlen = strlen(word);
16393 
16394       /* do completion for notify type */
16395 
16396       if (!notify_types)
16397          return NULL;
16398       
16399       while ( (cat = ast_category_browse(notify_types, cat)) ) {
16400          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
16401             c = ast_strdup(cat);
16402             break;
16403          }
16404       }
16405       return c;
16406    }
16407 
16408    if (pos > 2)
16409       return complete_sip_peer(word, state, 0);
16410 
16411    return NULL;
16412 }
16413 
16414 /*! \brief Show details of one active dialog */
16415 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16416 {
16417    struct sip_pvt *cur;
16418    size_t len;
16419    int found = 0;
16420    struct ao2_iterator i;
16421 
16422    switch (cmd) {
16423    case CLI_INIT:
16424       e->command = "sip show channel";
16425       e->usage =
16426          "Usage: sip show channel <call-id>\n"
16427          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
16428       return NULL;
16429    case CLI_GENERATE:
16430       return complete_sipch(a->line, a->word, a->pos, a->n);
16431    }
16432 
16433    if (a->argc != 4)
16434       return CLI_SHOWUSAGE;
16435    len = strlen(a->argv[3]);
16436    
16437    i = ao2_iterator_init(dialogs, 0);
16438    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16439       sip_pvt_lock(cur);
16440 
16441       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16442          char formatbuf[SIPBUFSIZE/2];
16443          ast_cli(a->fd, "\n");
16444          if (cur->subscribed != NONE)
16445             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
16446          else
16447             ast_cli(a->fd, "  * SIP Call\n");
16448          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
16449          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
16450          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
16451          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
16452          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
16453          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
16454          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
16455          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
16456          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
16457          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
16458          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
16459          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
16460          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
16461          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
16462          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
16463          ast_cli(a->fd, "  Audio IP:               %s %s\n", ast_inet_ntoa(cur->redirip.sin_addr.s_addr ? cur->redirip.sin_addr : cur->ourip.sin_addr), cur->redirip.sin_addr.s_addr ? "(Outside bridge)" : "(local)" );
16464          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
16465          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
16466          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
16467          if (!ast_strlen_zero(cur->username))
16468             ast_cli(a->fd, "  Username:               %s\n", cur->username);
16469          if (!ast_strlen_zero(cur->peername))
16470             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
16471          if (!ast_strlen_zero(cur->uri))
16472             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
16473          if (!ast_strlen_zero(cur->cid_num))
16474             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
16475          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
16476          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
16477          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
16478          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
16479          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
16480          ast_cli(a->fd, "  SIP Options:            ");
16481          if (cur->sipoptions) {
16482             int x;
16483             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
16484                if (cur->sipoptions & sip_options[x].id)
16485                   ast_cli(a->fd, "%s ", sip_options[x].text);
16486             }
16487             ast_cli(a->fd, "\n");
16488          } else
16489             ast_cli(a->fd, "(none)\n");
16490 
16491          if (!cur->stimer)
16492             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
16493          else {
16494             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
16495             if (cur->stimer->st_active == TRUE) {
16496                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
16497                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
16498                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
16499                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
16500                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
16501                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
16502                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
16503                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
16504                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
16505             }
16506          }
16507 
16508          ast_cli(a->fd, "\n\n");
16509 
16510          found++;
16511       }
16512 
16513       sip_pvt_unlock(cur);
16514 
16515       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
16516    }
16517    ao2_iterator_destroy(&i);
16518 
16519    if (!found) 
16520       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16521 
16522    return CLI_SUCCESS;
16523 }
16524 
16525 /*! \brief Show history details of one dialog */
16526 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16527 {
16528    struct sip_pvt *cur;
16529    size_t len;
16530    int found = 0;
16531    struct ao2_iterator i;
16532 
16533    switch (cmd) {
16534    case CLI_INIT:
16535       e->command = "sip show history";
16536       e->usage =
16537          "Usage: sip show history <call-id>\n"
16538          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
16539       return NULL;
16540    case CLI_GENERATE:
16541       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
16542    }
16543 
16544    if (a->argc != 4)
16545       return CLI_SHOWUSAGE;
16546 
16547    if (!recordhistory)
16548       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
16549 
16550    len = strlen(a->argv[3]);
16551 
16552    i = ao2_iterator_init(dialogs, 0);
16553    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
16554       sip_pvt_lock(cur);
16555       if (!strncasecmp(cur->callid, a->argv[3], len)) {
16556          struct sip_history *hist;
16557          int x = 0;
16558 
16559          ast_cli(a->fd, "\n");
16560          if (cur->subscribed != NONE)
16561             ast_cli(a->fd, "  * Subscription\n");
16562          else
16563             ast_cli(a->fd, "  * SIP Call\n");
16564          if (cur->history)
16565             AST_LIST_TRAVERSE(cur->history, hist, list)
16566                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
16567          if (x == 0)
16568             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
16569          found++;
16570       }
16571       sip_pvt_unlock(cur);
16572       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
16573    }
16574    ao2_iterator_destroy(&i);
16575 
16576    if (!found) 
16577       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
16578 
16579    return CLI_SUCCESS;
16580 }
16581 
16582 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
16583 static void sip_dump_history(struct sip_pvt *dialog)
16584 {
16585    int x = 0;
16586    struct sip_history *hist;
16587    static int errmsg = 0;
16588 
16589    if (!dialog)
16590       return;
16591 
16592    if (!option_debug && !sipdebug) {
16593       if (!errmsg) {
16594          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
16595          errmsg = 1;
16596       }
16597       return;
16598    }
16599 
16600    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
16601    if (dialog->subscribed)
16602       ast_debug(1, "  * Subscription\n");
16603    else
16604       ast_debug(1, "  * SIP Call\n");
16605    if (dialog->history)
16606       AST_LIST_TRAVERSE(dialog->history, hist, list)
16607          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
16608    if (!x)
16609       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
16610    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
16611 }
16612 
16613 
16614 /*! \brief  Receive SIP INFO Message */
16615 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
16616 {
16617    char buf[1024];
16618    unsigned int event;
16619    const char *c = get_header(req, "Content-Type");
16620 
16621    /* Need to check the media/type */
16622    if (!strcasecmp(c, "application/dtmf-relay") ||
16623        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
16624       unsigned int duration = 0;
16625 
16626       if (!p->owner) {  /* not a PBX call */
16627          transmit_response(p, "481 Call leg/transaction does not exist", req);
16628          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16629          return;
16630       }
16631 
16632       /* Try getting the "signal=" part */
16633       if (ast_strlen_zero(c = get_body(req, "Signal", '=')) && ast_strlen_zero(c = get_body(req, "d", '='))) {
16634          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
16635          transmit_response(p, "200 OK", req); /* Should return error */
16636          return;
16637       } else {
16638          ast_copy_string(buf, c, sizeof(buf));
16639       }
16640 
16641       if (!ast_strlen_zero((c = get_body(req, "Duration", '='))))
16642          duration = atoi(c);
16643       if (!duration)
16644          duration = 100; /* 100 ms */
16645 
16646 
16647       if (ast_strlen_zero(buf)) {
16648          transmit_response(p, "200 OK", req);
16649          return;
16650       }
16651 
16652       if (buf[0] == '*')
16653          event = 10;
16654       else if (buf[0] == '#')
16655          event = 11;
16656       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
16657          event = 12 + buf[0] - 'A';
16658       else if (buf[0] == '!')
16659          event = 16;
16660       else
16661          event = atoi(buf);
16662       if (event == 16) {
16663          /* send a FLASH event */
16664          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16665          ast_queue_frame(p->owner, &f);
16666          if (sipdebug)
16667             ast_verbose("* DTMF-relay event received: FLASH\n");
16668       } else {
16669          /* send a DTMF event */
16670          struct ast_frame f = { AST_FRAME_DTMF, };
16671          if (event < 10) {
16672             f.subclass = '0' + event;
16673          } else if (event < 11) {
16674             f.subclass = '*';
16675          } else if (event < 12) {
16676             f.subclass = '#';
16677          } else if (event < 16) {
16678             f.subclass = 'A' + (event - 12);
16679          }
16680          f.len = duration;
16681          ast_queue_frame(p->owner, &f);
16682          if (sipdebug)
16683             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16684       }
16685       transmit_response(p, "200 OK", req);
16686       return;
16687    } else if (!strcasecmp(c, "application/dtmf")) {
16688       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
16689       unsigned int duration = 0;
16690 
16691       if (!p->owner) {  /* not a PBX call */
16692          transmit_response(p, "481 Call leg/transaction does not exist", req);
16693          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16694          return;
16695       }
16696 
16697       get_msg_text(buf, sizeof(buf), req, TRUE);
16698       duration = 100; /* 100 ms */
16699 
16700       if (ast_strlen_zero(buf)) {
16701          transmit_response(p, "200 OK", req);
16702          return;
16703       }
16704       event = atoi(buf);
16705       if (event == 16) {
16706          /* send a FLASH event */
16707          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
16708          ast_queue_frame(p->owner, &f);
16709          if (sipdebug)
16710             ast_verbose("* DTMF-relay event received: FLASH\n");
16711       } else {
16712          /* send a DTMF event */
16713          struct ast_frame f = { AST_FRAME_DTMF, };
16714          if (event < 10) {
16715             f.subclass = '0' + event;
16716          } else if (event < 11) {
16717             f.subclass = '*';
16718          } else if (event < 12) {
16719             f.subclass = '#';
16720          } else if (event < 16) {
16721             f.subclass = 'A' + (event - 12);
16722          }
16723          f.len = duration;
16724          ast_queue_frame(p->owner, &f);
16725          if (sipdebug)
16726             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
16727       }
16728       transmit_response(p, "200 OK", req);
16729       return;
16730 
16731    } else if (!strcasecmp(c, "application/media_control+xml")) {
16732       /* Eh, we'll just assume it's a fast picture update for now */
16733       if (p->owner)
16734          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
16735       transmit_response(p, "200 OK", req);
16736       return;
16737    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
16738       /* Client code (from SNOM phone) */
16739       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
16740          if (p->owner && p->owner->cdr)
16741             ast_cdr_setuserfield(p->owner, c);
16742          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
16743             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
16744          transmit_response(p, "200 OK", req);
16745       } else {
16746          transmit_response(p, "403 Forbidden", req);
16747       }
16748       return;
16749    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
16750       /* INFO messages generated by some phones to start/stop recording
16751          on phone calls. 
16752          OEJ: I think this should be something that is enabled/disabled
16753          per device. I don't want incoming callers to record calls in my
16754          pbx.
16755       */
16756       /* first, get the feature string, if it exists */
16757       struct ast_call_feature *feat;
16758       int j;
16759       struct ast_frame f = { AST_FRAME_DTMF, };
16760 
16761       ast_rdlock_call_features();
16762       feat = ast_find_call_feature("automon");
16763       if (!feat || ast_strlen_zero(feat->exten)) {
16764          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
16765          /* 403 means that we don't support this feature, so don't request it again */
16766          transmit_response(p, "403 Forbidden", req);
16767          ast_unlock_call_features();
16768          return;
16769       } 
16770       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
16771       f.len = 100;
16772       for (j=0; j < strlen(feat->exten); j++) {
16773          f.subclass = feat->exten[j];
16774          ast_queue_frame(p->owner, &f);
16775          if (sipdebug)
16776             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
16777       }
16778       ast_unlock_call_features();
16779 
16780       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
16781       transmit_response(p, "200 OK", req);
16782       return;
16783    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
16784       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
16785       transmit_response(p, "200 OK", req);
16786       return;
16787    }
16788 
16789    /* Other type of INFO message, not really understood by Asterisk */
16790    /* if (get_msg_text(buf, sizeof(buf), req)) { */
16791 
16792    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
16793    transmit_response(p, "415 Unsupported media type", req);
16794    return;
16795 }
16796 
16797 /*! \brief Enable SIP Debugging for a single IP */
16798 static char *sip_do_debug_ip(int fd, char *arg)
16799 {
16800    struct hostent *hp;
16801    struct ast_hostent ahp;
16802    int port = 0;
16803    char *p;
16804 
16805    p = arg;
16806    strsep(&p, ":");
16807    if (p)
16808       port = atoi(p);
16809    hp = ast_gethostbyname(arg, &ahp);
16810    if (hp == NULL)
16811       return CLI_SHOWUSAGE;
16812 
16813    debugaddr.sin_family = AF_INET;
16814    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
16815    debugaddr.sin_port = htons(port);
16816    if (port == 0)
16817       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
16818    else
16819       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
16820 
16821    sipdebug |= sip_debug_console;
16822 
16823    return CLI_SUCCESS;
16824 }
16825 
16826 /*! \brief  Turn on SIP debugging for a given peer */
16827 static char *sip_do_debug_peer(int fd, char *arg)
16828 {
16829    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
16830    if (!peer)
16831       ast_cli(fd, "No such peer '%s'\n", arg);
16832    else if (peer->addr.sin_addr.s_addr == 0)
16833       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
16834    else {
16835       debugaddr.sin_family = AF_INET;
16836       debugaddr.sin_addr = peer->addr.sin_addr;
16837       debugaddr.sin_port = peer->addr.sin_port;
16838       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
16839          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
16840       sipdebug |= sip_debug_console;
16841    }
16842    if (peer)
16843       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16844    return CLI_SUCCESS;
16845 }
16846 
16847 /*! \brief Turn on SIP debugging (CLI command) */
16848 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16849 {
16850    int oldsipdebug = sipdebug & sip_debug_console;
16851    char *what;
16852 
16853    if (cmd == CLI_INIT) {
16854       e->command = "sip set debug {on|off|ip|peer}";
16855       e->usage =
16856          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16857          "       Globally disables dumping of SIP packets,\n"
16858          "       or enables it either globally or for a (single)\n"
16859          "       IP address or registered peer.\n";
16860       return NULL;
16861    } else if (cmd == CLI_GENERATE) {
16862       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) 
16863          return complete_sip_peer(a->word, a->n, 0);
16864       return NULL;
16865         }
16866 
16867    what = a->argv[e->args-1];      /* guaranteed to exist */
16868    if (a->argc == e->args) {       /* on/off */
16869       if (!strcasecmp(what, "on")) {
16870          sipdebug |= sip_debug_console;
16871          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
16872          memset(&debugaddr, 0, sizeof(debugaddr));
16873          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16874          return CLI_SUCCESS;
16875       } else if (!strcasecmp(what, "off")) {
16876          sipdebug &= ~sip_debug_console;
16877          sipdebug_text = 0;
16878          ast_cli(a->fd, "SIP Debugging Disabled\n");
16879          return CLI_SUCCESS;
16880       }
16881    } else if (a->argc == e->args +1) {/* ip/peer */
16882       if (!strcasecmp(what, "ip"))
16883          return sip_do_debug_ip(a->fd, a->argv[e->args]);
16884       else if (!strcasecmp(what, "peer"))
16885          return sip_do_debug_peer(a->fd, a->argv[e->args]);
16886    }
16887    return CLI_SHOWUSAGE;   /* default, failure */
16888 }
16889 
16890 /*! \brief Cli command to send SIP notify to peer */
16891 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16892 {
16893    struct ast_variable *varlist;
16894    int i;
16895 
16896    switch (cmd) {
16897    case CLI_INIT:
16898       e->command = "sip notify";
16899       e->usage =
16900          "Usage: sip notify <type> <peer> [<peer>...]\n"
16901          "       Send a NOTIFY message to a SIP peer or peers\n"
16902          "       Message types are defined in sip_notify.conf\n";
16903       return NULL;
16904    case CLI_GENERATE:
16905       return complete_sipnotify(a->line, a->word, a->pos, a->n);
16906    }
16907 
16908    if (a->argc < 4)
16909       return CLI_SHOWUSAGE;
16910 
16911    if (!notify_types) {
16912       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
16913       return CLI_FAILURE;
16914    }
16915 
16916    varlist = ast_variable_browse(notify_types, a->argv[2]);
16917 
16918    if (!varlist) {
16919       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
16920       return CLI_FAILURE;
16921    }
16922 
16923    for (i = 3; i < a->argc; i++) {
16924       struct sip_pvt *p;
16925 
16926       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
16927          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
16928          return CLI_FAILURE;
16929       }
16930 
16931       if (create_addr(p, a->argv[i], NULL, 1)) {
16932          /* Maybe they're not registered, etc. */
16933          dialog_unlink_all(p, TRUE, TRUE);
16934          dialog_unref(p, "unref dialog inside for loop" );
16935          /* sip_destroy(p); */
16936          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
16937          continue;
16938       }
16939 
16940       /* Notify is outgoing call */
16941       ast_set_flag(&p->flags[0], SIP_OUTGOING);
16942 
16943       /* Recalculate our side, and recalculate Call ID */
16944       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
16945       build_via(p);
16946       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
16947       build_callid_pvt(p);
16948       ao2_t_link(dialogs, p, "Linking in new name");
16949       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
16950       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
16951       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
16952       transmit_notify_custom(p, varlist);
16953    }
16954 
16955    return CLI_SUCCESS;
16956 }
16957 
16958 /*! \brief Enable/Disable SIP History logging (CLI) */
16959 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16960 {
16961    switch (cmd) {
16962    case CLI_INIT:
16963       e->command = "sip set history {on|off}";
16964       e->usage =
16965          "Usage: sip set history {on|off}\n"
16966          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
16967          "       Use 'sip show history' to view the history of a call number.\n";
16968       return NULL;
16969    case CLI_GENERATE:
16970       return NULL;
16971    }
16972 
16973    if (a->argc != e->args)
16974       return CLI_SHOWUSAGE;
16975 
16976    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
16977       recordhistory = TRUE;
16978       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
16979    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
16980       recordhistory = FALSE;
16981       ast_cli(a->fd, "SIP History Recording Disabled\n");
16982    } else {
16983       return CLI_SHOWUSAGE;
16984    }
16985    return CLI_SUCCESS;
16986 }
16987 
16988 /*! \brief Authenticate for outbound registration */
16989 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
16990 {
16991    char *header, *respheader;
16992    char digest[1024];
16993 
16994    p->authtries++;
16995    auth_headers(code, &header, &respheader);
16996    memset(digest, 0, sizeof(digest));
16997    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
16998       /* There's nothing to use for authentication */
16999       /* No digest challenge in request */
17000       if (sip_debug_test_pvt(p) && p->registry)
17001          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
17002          /* No old challenge */
17003       return -1;
17004    }
17005    if (p->do_history)
17006       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
17007    if (sip_debug_test_pvt(p) && p->registry)
17008       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
17009    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
17010 }
17011 
17012 /*! \brief Add authentication on outbound SIP packet */
17013 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
17014 {
17015    char *header, *respheader;
17016    char digest[1024];
17017 
17018    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
17019       return -2;
17020 
17021    p->authtries++;
17022    auth_headers(code, &header, &respheader);
17023    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
17024    memset(digest, 0, sizeof(digest));
17025    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
17026       /* No way to authenticate */
17027       return -1;
17028    }
17029    /* Now we have a reply digest */
17030    p->options->auth = digest;
17031    p->options->authheader = respheader;
17032    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
17033 }
17034 
17035 /*! \brief  reply to authentication for outbound registrations
17036 \return  Returns -1 if we have no auth 
17037 \note This is used for register= servers in sip.conf, SIP proxies we register
17038    with  for receiving calls from.  */
17039 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
17040 {
17041    char tmp[512];
17042    char *c;
17043    char oldnonce[256];
17044 
17045    /* table of recognised keywords, and places where they should be copied */
17046    const struct x {
17047       const char *key;
17048       const ast_string_field *field;
17049    } *i, keys[] = {
17050       { "realm=", &p->realm },
17051       { "nonce=", &p->nonce },
17052       { "opaque=", &p->opaque },
17053       { "qop=", &p->qop },
17054       { "domain=", &p->domain },
17055       { NULL, 0 },
17056    };
17057 
17058    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
17059    if (ast_strlen_zero(tmp)) 
17060       return -1;
17061    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
17062       ast_log(LOG_WARNING, "missing Digest.\n");
17063       return -1;
17064    }
17065    c = tmp + strlen("Digest ");
17066    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
17067    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
17068       for (i = keys; i->key != NULL; i++) {
17069          char *src, *separator;
17070          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
17071             continue;
17072          /* Found. Skip keyword, take text in quotes or up to the separator. */
17073          c += strlen(i->key);
17074          if (*c == '"') {
17075             src = ++c;
17076             separator = "\"";
17077          } else {
17078             src = c;
17079             separator = ",";
17080          }
17081          strsep(&c, separator); /* clear separator and move ptr */
17082          ast_string_field_ptr_set(p, i->field, src);
17083          break;
17084       }
17085       if (i->key == NULL) /* not found, try ',' */
17086          strsep(&c, ",");
17087    }
17088    /* Reset nonce count */
17089    if (strcmp(p->nonce, oldnonce)) 
17090       p->noncecount = 0;
17091 
17092    /* Save auth data for following registrations */
17093    if (p->registry) {
17094       struct sip_registry *r = p->registry;
17095 
17096       if (strcmp(r->nonce, p->nonce)) {
17097          ast_string_field_set(r, realm, p->realm);
17098          ast_string_field_set(r, nonce, p->nonce);
17099          ast_string_field_set(r, domain, p->domain);
17100          ast_string_field_set(r, opaque, p->opaque);
17101          ast_string_field_set(r, qop, p->qop);
17102          r->noncecount = 0;
17103       }
17104    }
17105    return build_reply_digest(p, sipmethod, digest, digest_len); 
17106 }
17107 
17108 /*! \brief  Build reply digest 
17109 \return  Returns -1 if we have no auth 
17110 \note Build digest challenge for authentication of registrations and calls
17111    Also used for authentication of BYE 
17112 */
17113 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
17114 {
17115    char a1[256];
17116    char a2[256];
17117    char a1_hash[256];
17118    char a2_hash[256];
17119    char resp[256];
17120    char resp_hash[256];
17121    char uri[256];
17122    char opaque[256] = "";
17123    char cnonce[80];
17124    const char *username;
17125    const char *secret;
17126    const char *md5secret;
17127    struct sip_auth *auth = NULL; /* Realm authentication */
17128 
17129    if (!ast_strlen_zero(p->domain))
17130       ast_copy_string(uri, p->domain, sizeof(uri));
17131    else if (!ast_strlen_zero(p->uri))
17132       ast_copy_string(uri, p->uri, sizeof(uri));
17133    else
17134       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
17135 
17136    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
17137 
17138    /* Check if we have separate auth credentials */
17139    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
17140       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
17141 
17142    if (auth) {
17143       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
17144       username = auth->username;
17145       secret = auth->secret;
17146       md5secret = auth->md5secret;
17147       if (sipdebug)
17148          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
17149    } else {
17150       /* No authentication, use peer or register= config */
17151       username = p->authname;
17152       secret =  p->peersecret;
17153       md5secret = p->peermd5secret;
17154    }
17155    if (ast_strlen_zero(username))   /* We have no authentication */
17156       return -1;
17157 
17158    /* Calculate SIP digest response */
17159    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
17160    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
17161    if (!ast_strlen_zero(md5secret))
17162       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
17163    else
17164       ast_md5_hash(a1_hash, a1);
17165    ast_md5_hash(a2_hash, a2);
17166 
17167    p->noncecount++;
17168    if (!ast_strlen_zero(p->qop))
17169       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
17170    else
17171       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
17172    ast_md5_hash(resp_hash, resp);
17173 
17174    /* only include the opaque string if it's set */
17175    if (!ast_strlen_zero(p->opaque)) {
17176      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
17177    }
17178 
17179    /* XXX We hard code our qop to "auth" for now.  XXX */
17180    if (!ast_strlen_zero(p->qop))
17181       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
17182    else
17183       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
17184 
17185    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
17186 
17187    return 0;
17188 }
17189    
17190 /*! \brief Read SIP header (dialplan function) */
17191 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
17192 {
17193    struct sip_pvt *p;
17194    const char *content = NULL;
17195    AST_DECLARE_APP_ARGS(args,
17196       AST_APP_ARG(header);
17197       AST_APP_ARG(number);
17198    );
17199    int i, number, start = 0;
17200 
17201    if (ast_strlen_zero(data)) {
17202       ast_log(LOG_WARNING, "This function requires a header name.\n");
17203       return -1;
17204    }
17205 
17206    ast_channel_lock(chan);
17207    if (!IS_SIP_TECH(chan->tech)) {
17208       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17209       ast_channel_unlock(chan);
17210       return -1;
17211    }
17212 
17213    AST_STANDARD_APP_ARGS(args, data);
17214    if (!args.number) {
17215       number = 1;
17216    } else {
17217       sscanf(args.number, "%30d", &number);
17218       if (number < 1)
17219          number = 1;
17220    }
17221 
17222    p = chan->tech_pvt;
17223 
17224    /* If there is no private structure, this channel is no longer alive */
17225    if (!p) {
17226       ast_channel_unlock(chan);
17227       return -1;
17228    }
17229 
17230    for (i = 0; i < number; i++)
17231       content = __get_header(&p->initreq, args.header, &start);
17232 
17233    if (ast_strlen_zero(content)) {
17234       ast_channel_unlock(chan);
17235       return -1;
17236    }
17237 
17238    ast_copy_string(buf, content, len);
17239    ast_channel_unlock(chan);
17240 
17241    return 0;
17242 }
17243 
17244 static struct ast_custom_function sip_header_function = {
17245    .name = "SIP_HEADER",
17246    .read = func_header_read,
17247 };
17248 
17249 /*! \brief  Dial plan function to check if domain is local */
17250 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17251 {
17252    if (ast_strlen_zero(data)) {
17253       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
17254       return -1;
17255    }
17256    if (check_sip_domain(data, NULL, 0))
17257       ast_copy_string(buf, data, len);
17258    else
17259       buf[0] = '\0';
17260    return 0;
17261 }
17262 
17263 static struct ast_custom_function checksipdomain_function = {
17264    .name = "CHECKSIPDOMAIN",
17265    .read = func_check_sipdomain,
17266 };
17267 
17268 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
17269 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17270 {
17271    struct sip_peer *peer;
17272    char *colname;
17273 
17274    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
17275       static int deprecation_warning = 0;
17276       *colname++ = '\0';
17277       if (deprecation_warning++ % 10 == 0)
17278          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
17279    } else if ((colname = strchr(data, ',')))
17280       *colname++ = '\0';
17281    else
17282       colname = "ip";
17283 
17284    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
17285       return -1;
17286 
17287    if (!strcasecmp(colname, "ip")) {
17288       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
17289    } else  if (!strcasecmp(colname, "port")) {
17290       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
17291    } else  if (!strcasecmp(colname, "status")) {
17292       peer_status(peer, buf, len);
17293    } else  if (!strcasecmp(colname, "language")) {
17294       ast_copy_string(buf, peer->language, len);
17295    } else  if (!strcasecmp(colname, "regexten")) {
17296       ast_copy_string(buf, peer->regexten, len);
17297    } else  if (!strcasecmp(colname, "limit")) {
17298       snprintf(buf, len, "%d", peer->call_limit);
17299    } else  if (!strcasecmp(colname, "busylevel")) {
17300       snprintf(buf, len, "%d", peer->busy_level);
17301    } else  if (!strcasecmp(colname, "curcalls")) {
17302       snprintf(buf, len, "%d", peer->inUse);
17303    } else  if (!strcasecmp(colname, "accountcode")) {
17304       ast_copy_string(buf, peer->accountcode, len);
17305    } else  if (!strcasecmp(colname, "callgroup")) {
17306       ast_print_group(buf, len, peer->callgroup);
17307    } else  if (!strcasecmp(colname, "pickupgroup")) {
17308       ast_print_group(buf, len, peer->pickupgroup);
17309    } else  if (!strcasecmp(colname, "useragent")) {
17310       ast_copy_string(buf, peer->useragent, len);
17311    } else  if (!strcasecmp(colname, "mailbox")) {
17312       struct ast_str *mailbox_str = ast_str_alloca(512);
17313       peer_mailboxes_to_str(&mailbox_str, peer);
17314       ast_copy_string(buf, mailbox_str->str, len);
17315    } else  if (!strcasecmp(colname, "context")) {
17316       ast_copy_string(buf, peer->context, len);
17317    } else  if (!strcasecmp(colname, "expire")) {
17318       snprintf(buf, len, "%d", peer->expire);
17319    } else  if (!strcasecmp(colname, "dynamic")) {
17320       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
17321    } else  if (!strcasecmp(colname, "callerid_name")) {
17322       ast_copy_string(buf, peer->cid_name, len);
17323    } else  if (!strcasecmp(colname, "callerid_num")) {
17324       ast_copy_string(buf, peer->cid_num, len);
17325    } else  if (!strcasecmp(colname, "codecs")) {
17326       ast_getformatname_multiple(buf, len -1, peer->capability);
17327    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
17328       char *chanvar=colname + 8;
17329       struct ast_variable *v;
17330    
17331       chanvar = strsep(&chanvar, "]");
17332       for (v = peer->chanvars ; v ; v = v->next) {
17333          if (!strcasecmp(v->name, chanvar)) {
17334             ast_copy_string(buf, v->value, len);
17335          }
17336       }
17337    } else  if (!strncasecmp(colname, "codec[", 6)) {
17338       char *codecnum;
17339       int codec = 0;
17340       
17341       codecnum = colname + 6; /* move past the '[' */
17342       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
17343       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
17344          ast_copy_string(buf, ast_getformatname(codec), len);
17345       } else {
17346          buf[0] = '\0';
17347       }
17348    } else {
17349       buf[0] = '\0';
17350    }
17351 
17352    unref_peer(peer, "unref_peer from function_sippeer, just before return");
17353 
17354    return 0;
17355 }
17356 
17357 /*! \brief Structure to declare a dialplan function: SIPPEER */
17358 static struct ast_custom_function sippeer_function = {
17359    .name = "SIPPEER",
17360    .read = function_sippeer,
17361 };
17362 
17363 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
17364 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
17365 {
17366    struct sip_pvt *p;
17367    static int deprecated = 0;
17368 
17369    *buf = 0;
17370    
17371    if (!data) {
17372       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
17373       return -1;
17374    }
17375 
17376    ast_channel_lock(chan);
17377    if (!IS_SIP_TECH(chan->tech)) {
17378       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
17379       ast_channel_unlock(chan);
17380       return -1;
17381    }
17382 
17383    if (deprecated++ % 20 == 0) {
17384       /* Deprecated in 1.6.1 */
17385       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
17386    }
17387 
17388    p = chan->tech_pvt;
17389 
17390    /* If there is no private structure, this channel is no longer alive */
17391    if (!p) {
17392       ast_channel_unlock(chan);
17393       return -1;
17394    }
17395 
17396    if (!strcasecmp(data, "peerip")) {
17397       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
17398    } else  if (!strcasecmp(data, "recvip")) {
17399       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
17400    } else  if (!strcasecmp(data, "from")) {
17401       ast_copy_string(buf, p->from, len);
17402    } else  if (!strcasecmp(data, "uri")) {
17403       ast_copy_string(buf, p->uri, len);
17404    } else  if (!strcasecmp(data, "useragent")) {
17405       ast_copy_string(buf, p->useragent, len);
17406    } else  if (!strcasecmp(data, "peername")) {
17407       ast_copy_string(buf, p->peername, len);
17408    } else if (!strcasecmp(data, "t38passthrough")) {
17409       if (p->t38.state == T38_DISABLED) {
17410          ast_copy_string(buf, "0", len);
17411       } else { /* T38 is offered or enabled in this call */
17412          ast_copy_string(buf, "1", len);
17413       }
17414    } else {
17415       ast_channel_unlock(chan);
17416       return -1;
17417    }
17418    ast_channel_unlock(chan);
17419 
17420    return 0;
17421 }
17422 
17423 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
17424 static struct ast_custom_function sipchaninfo_function = {
17425    .name = "SIPCHANINFO",
17426    .read = function_sipchaninfo_read,
17427 };
17428 
17429 /*! \brief Parse 302 Moved temporalily response 
17430    \todo XXX Doesn't redirect over TLS on sips: uri's.
17431       If we get a redirect to a SIPS: uri, this needs to be going back to the
17432       dialplan (this is a request for a secure signalling path).
17433       Note that transport=tls is deprecated, but we need to support it on incoming requests.
17434 */
17435 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
17436 {
17437    char tmp[SIPBUFSIZE];
17438    char *s, *e, *t, *trans;
17439    char *domain;
17440    enum sip_transport transport = SIP_TRANSPORT_UDP;
17441 
17442    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
17443    if ((t = strchr(tmp, ',')))
17444       *t = '\0';
17445 
17446    s = get_in_brackets(tmp);
17447    if ((trans = strcasestr(s, ";transport="))) do {
17448       trans += 11;
17449 
17450       if ((e = strchr(trans, ';')))
17451          *e = '\0';
17452 
17453       if (!strncasecmp(trans, "tcp", 3))
17454          transport = SIP_TRANSPORT_TCP;
17455       else if (!strncasecmp(trans, "tls", 3))
17456          transport = SIP_TRANSPORT_TLS;
17457       else {
17458          if (strncasecmp(trans, "udp", 3))
17459             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
17460          /* This will assume UDP for all unknown transports */
17461          transport = SIP_TRANSPORT_UDP;
17462       }
17463    } while(0);
17464    s = remove_uri_parameters(s);
17465 
17466    if (p->socket.tcptls_session) {
17467       ao2_ref(p->socket.tcptls_session, -1);
17468       p->socket.tcptls_session = NULL;
17469    }
17470 
17471    set_socket_transport(&p->socket, transport);
17472 
17473    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
17474       char *host = NULL;
17475       if (!strncasecmp(s, "sip:", 4))
17476          s += 4;
17477       else if (!strncasecmp(s, "sips:", 5))
17478          s += 5;
17479       e = strchr(s, '/');
17480       if (e)
17481          *e = '\0';
17482       if ((host = strchr(s, '@'))) {
17483          *host++ = '\0';
17484          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
17485          if (p->owner)
17486             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
17487       } else {
17488          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
17489          if (p->owner)
17490             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
17491       }
17492    } else {
17493       e = strchr(tmp, '@');
17494       if (e) {
17495          *e++ = '\0';
17496          domain = e;
17497       } else {
17498          /* No username part */
17499          domain = tmp;
17500       }
17501       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
17502       if (e)
17503          *e = '\0';
17504 
17505       if (!strncasecmp(s, "sip:", 4))
17506          s += 4;
17507       else if (!strncasecmp(s, "sips:", 5))
17508          s += 5;
17509       e = strchr(s, ';');  /* And username ; parameters? */
17510       if (e)
17511          *e = '\0';  
17512       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
17513       if (p->owner) {
17514          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
17515          ast_string_field_set(p->owner, call_forward, s);
17516       }
17517    }
17518 }
17519 
17520 /*! \brief Check pending actions on SIP call */
17521 static void check_pendings(struct sip_pvt *p)
17522 {
17523    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
17524       /* if we can't BYE, then this is really a pending CANCEL */
17525       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
17526          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
17527          /* Actually don't destroy us yet, wait for the 487 on our original 
17528             INVITE, but do set an autodestruct just in case we never get it. */
17529       else {
17530          /* We have a pending outbound invite, don't send something
17531             new in-transaction */
17532          if (p->pendinginvite)
17533             return;
17534 
17535          /* Perhaps there is an SD change INVITE outstanding */
17536          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
17537       }
17538       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
17539       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17540    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
17541       /* if we can't REINVITE, hold it for later */
17542       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
17543          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
17544       } else {
17545          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
17546          /* Didn't get to reinvite yet, so do it now */
17547          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
17548          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
17549       }
17550    }
17551 }
17552 
17553 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
17554    to avoid race conditions between asterisk servers.
17555    Called from the scheduler.
17556 */
17557 static int sip_reinvite_retry(const void *data)
17558 {
17559    struct sip_pvt *p = (struct sip_pvt *) data;
17560 
17561    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
17562    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
17563    p->waitid = -1;
17564    check_pendings(p);
17565    sip_pvt_unlock(p);
17566    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
17567    return 0;
17568 }
17569 
17570 
17571 /*! \brief Handle SIP response to INVITE dialogue */
17572 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17573 {
17574    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
17575    int res = 0;
17576    int xmitres = 0;
17577    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
17578    char *p_hdrval;
17579    int rtn;
17580 
17581    if (reinvite)
17582       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
17583    else
17584       ast_debug(4, "SIP response %d to standard invite\n", resp);
17585 
17586    if (p->alreadygone) { /* This call is already gone */
17587       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
17588       return;
17589    }
17590 
17591    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
17592    /* Don't auto congest anymore since we've gotten something useful back */
17593    AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
17594 
17595    /* RFC3261 says we must treat every 1xx response (but not 100)
17596       that we don't recognize as if it was 183.
17597    */
17598    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
17599       resp = 183;
17600 
17601    /* Any response between 100 and 199 is PROCEEDING */
17602    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
17603       p->invitestate = INV_PROCEEDING;
17604  
17605    /* Final response, not 200 ? */
17606    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
17607       p->invitestate = INV_COMPLETED;
17608    
17609    /* Final response, clear out pending invite */
17610    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
17611       p->pendinginvite = 0;
17612 
17613    switch (resp) {
17614    case 100:   /* Trying */
17615    case 101:   /* Dialog establishment */
17616       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17617          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17618       check_pendings(p);
17619       break;
17620 
17621    case 180:   /* 180 Ringing */
17622    case 182:       /* 182 Queued */
17623       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
17624          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17625       if (!req->ignore && p->owner) {
17626          ast_queue_control(p->owner, AST_CONTROL_RINGING);
17627          if (p->owner->_state != AST_STATE_UP) {
17628             ast_setstate(p->owner, AST_STATE_RINGING);
17629          }
17630       }
17631       if (find_sdp(req)) {
17632          if (p->invitestate != INV_CANCELLED)
17633             p->invitestate = INV_EARLY_MEDIA;
17634          res = process_sdp(p, req, SDP_T38_NONE);
17635          if (!req->ignore && p->owner) {
17636             /* Queue a progress frame only if we have SDP in 180 or 182 */
17637             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17638          }
17639       }
17640       check_pendings(p);
17641       break;
17642 
17643    case 183:   /* Session progress */
17644       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17645          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17646       if (find_sdp(req)) {
17647          if (p->invitestate != INV_CANCELLED)
17648             p->invitestate = INV_EARLY_MEDIA;
17649          res = process_sdp(p, req, SDP_T38_NONE);
17650          if (!req->ignore && p->owner) {
17651             /* Queue a progress frame */
17652             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17653          }
17654       } else {
17655          /* Alcatel PBXs are known to send 183s with no SDP after sending
17656           * a 100 Trying response. We're just going to treat this sort of thing
17657           * the same as we would treat a 180 Ringing
17658           */
17659          if (!req->ignore && p->owner) {
17660             ast_queue_control(p->owner, AST_CONTROL_RINGING);
17661          }
17662       }
17663       check_pendings(p);
17664       break;
17665 
17666    case 200:   /* 200 OK on invite - someone's answering our call */
17667       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
17668          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17669       p->authtries = 0;
17670       if (find_sdp(req)) {
17671          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
17672             if (!reinvite)
17673                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
17674                /* For re-invites, we try to recover */
17675                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17676       }
17677 
17678       /* Parse contact header for continued conversation */
17679       /* When we get 200 OK, we know which device (and IP) to contact for this call */
17680       /* This is important when we have a SIP proxy between us and the phone */
17681       if (outgoing) {
17682          update_call_counter(p, DEC_CALL_RINGING);
17683          parse_ok_contact(p, req);
17684          /* Save Record-Route for any later requests we make on this dialogue */
17685          if (!reinvite)
17686             build_route(p, req, 1);
17687 
17688          if(set_address_from_contact(p)) {
17689             /* Bad contact - we don't know how to reach this device */
17690             /* We need to ACK, but then send a bye */
17691             if (!p->route && !req->ignore)
17692                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17693          } 
17694 
17695       }
17696 
17697       if (!req->ignore && p->owner) {
17698          if (!reinvite) {
17699             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
17700             if (sip_cfg.callevents)
17701                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
17702                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
17703                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
17704          } else { /* RE-invite */
17705             ast_queue_frame(p->owner, &ast_null_frame);
17706          }
17707       } else {
17708           /* It's possible we're getting an 200 OK after we've tried to disconnect
17709               by sending CANCEL */
17710          /* First send ACK, then send bye */
17711          if (!req->ignore)
17712             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17713       }
17714 
17715       /* Check for Session-Timers related headers */
17716       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
17717          p_hdrval = (char*)get_header(req, "Session-Expires");
17718             if (!ast_strlen_zero(p_hdrval)) {
17719             /* UAS supports Session-Timers */
17720             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
17721             int tmp_st_interval = 0;
17722             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
17723             if (rtn != 0) {
17724                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
17725             }
17726             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
17727                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
17728                p->stimer->st_ref = tmp_st_ref;
17729             } 
17730             if (tmp_st_interval) {
17731                p->stimer->st_interval = tmp_st_interval;
17732             }
17733             p->stimer->st_active = TRUE;
17734             p->stimer->st_active_peer_ua = TRUE;
17735             start_session_timer(p);
17736          } else {
17737             /* UAS doesn't support Session-Timers */
17738             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
17739                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
17740                p->stimer->st_active_peer_ua = FALSE;
17741                start_session_timer(p);
17742             }
17743          }
17744       }
17745 
17746 
17747       /* If I understand this right, the branch is different for a non-200 ACK only */
17748       p->invitestate = INV_TERMINATED;
17749       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17750       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
17751       check_pendings(p);
17752       break;
17753 
17754    case 407: /* Proxy authentication */
17755    case 401: /* Www auth */
17756       /* First we ACK */
17757       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17758       if (p->options)
17759          p->options->auth_type = resp;
17760 
17761       /* Then we AUTH */
17762       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
17763       if (!req->ignore) {
17764          if (p->authtries < MAX_AUTHTRIES)
17765             p->invitestate = INV_CALLING;
17766          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
17767             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
17768             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
17769             sip_alreadygone(p);
17770             if (p->owner)
17771                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17772          }
17773       }
17774       break;
17775 
17776    case 403: /* Forbidden */
17777       /* First we ACK */
17778       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17779       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17780       if (!req->ignore && p->owner)
17781          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17782       pvt_set_needdestroy(p, "received 403 response");
17783       sip_alreadygone(p);
17784       break;
17785 
17786    case 404: /* Not found */
17787       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17788       if (p->owner && !req->ignore)
17789          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17790       sip_alreadygone(p);
17791       break;
17792 
17793    case 408: /* Request timeout */
17794    case 481: /* Call leg does not exist */
17795       /* Could be REFER caused INVITE with replaces */
17796       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17797       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17798       if (p->owner)
17799          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17800       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17801       break;
17802 
17803    case 422: /* Session-Timers: Session interval too small */
17804       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17805       ast_string_field_set(p, theirtag, NULL);
17806       proc_422_rsp(p, req);
17807       break;
17808 
17809    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
17810       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17811       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
17812       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
17813       if (p->owner)
17814          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17815       break;
17816 
17817       
17818 
17819    case 487: /* Cancelled transaction */
17820       /* We have sent CANCEL on an outbound INVITE 
17821          This transaction is already scheduled to be killed by sip_hangup().
17822       */
17823       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17824       if (p->owner && !req->ignore) {
17825          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17826          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17827       } else if (!req->ignore) {
17828          update_call_counter(p, DEC_CALL_LIMIT);
17829          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17830          pvt_set_needdestroy(p, "received 487 response");
17831          sip_alreadygone(p);
17832       }
17833       break;
17834    case 415: /* Unsupported media type */
17835    case 488: /* Not acceptable here */
17836    case 606: /* Not Acceptable */
17837       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17838       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17839          change_t38_state(p, T38_DISABLED);
17840          /* Try to reset RTP timers */
17841          ast_rtp_set_rtptimers_onhold(p->rtp);
17842 
17843          /* Trigger a reinvite back to audio */
17844          transmit_reinvite_with_sdp(p, FALSE, FALSE);
17845       } else {
17846          /* We can't set up this call, so give up */
17847          if (p->owner && !req->ignore)
17848             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17849          pvt_set_needdestroy(p, "received 488 response");
17850          /* If there's no dialog to end, then mark p as already gone */
17851          if (!reinvite)
17852             sip_alreadygone(p);
17853       }
17854       break;
17855    case 491: /* Pending */
17856       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17857       if (p->owner && !req->ignore) {
17858          if (p->owner->_state != AST_STATE_UP) {
17859             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17860             pvt_set_needdestroy(p, "received 491 response");
17861          } else {
17862             /* This is a re-invite that failed. */
17863             /* Reset the flag after a while 
17864              */
17865             int wait;
17866             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
17867              * if not owner of call, wait 0 to 2 seconds */
17868             if (p->outgoing_call) {
17869                wait = 2100 + ast_random() % 2000;
17870             } else {
17871                wait = ast_random() % 2000;
17872             }
17873             p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
17874             ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
17875             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17876          }
17877       }
17878       break;
17879 
17880    case 501: /* Not implemented */
17881       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17882       if (p->owner)
17883          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17884       break;
17885    }
17886    if (xmitres == XMIT_ERROR)
17887       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17888 }
17889 
17890 /* \brief Handle SIP response in NOTIFY transaction
17891        We've sent a NOTIFY, now handle responses to it
17892   */
17893 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17894 {
17895    switch (resp) {
17896    case 200:   /* Notify accepted */
17897       /* They got the notify, this is the end */
17898       if (p->owner) {
17899          if (!p->refer) {
17900             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17901             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17902          } else {
17903             ast_debug(4, "Got OK on REFER Notify message\n");
17904          }
17905       } else {
17906          if (p->subscribed == NONE) {
17907             ast_debug(4, "Got 200 accepted on NOTIFY\n");
17908             pvt_set_needdestroy(p, "received 200 response");
17909          }
17910          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17911             /* Ready to send the next state we have on queue */
17912             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17913             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17914          }
17915       }
17916       break;
17917    case 401:   /* Not www-authorized on SIP method */
17918    case 407:   /* Proxy auth */
17919       if (!p->notify_headers) {
17920          break; /* Only device notify can use NOTIFY auth */
17921       }
17922       ast_string_field_set(p, theirtag, NULL);
17923       if (ast_strlen_zero(p->authname)) {
17924          ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s:%d but we have no matching peer or realm auth!\n", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17925          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
17926       }
17927       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
17928          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
17929          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
17930       }
17931       break;
17932    }
17933 }
17934 
17935 /* \brief Handle SIP response in SUBSCRIBE transaction */
17936 static void handle_response_subscribe(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17937 {
17938    if (!p->mwi) {
17939       return;
17940    }
17941 
17942    switch (resp) {
17943    case 200: /* Subscription accepted */
17944       ast_debug(3, "Got 200 OK on subscription for MWI\n");
17945       if (p->options) {
17946          ast_free(p->options);
17947          p->options = NULL;
17948       }
17949       p->mwi->subscribed = 1;
17950       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
17951          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17952       }
17953       break;
17954    case 401:
17955    case 407:
17956       ast_string_field_set(p, theirtag, NULL);
17957       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
17958          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
17959          p->mwi->call = NULL;
17960          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17961          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
17962       }
17963       break;
17964    case 403:
17965       transmit_response_with_date(p, "200 OK", req);
17966       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
17967       p->mwi->call = NULL;
17968       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17969       pvt_set_needdestroy(p, "received 403 response");
17970       sip_alreadygone(p);
17971       break;
17972    case 404:
17973       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
17974       p->mwi->call = NULL;
17975       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17976       pvt_set_needdestroy(p, "received 404 response");
17977       break;
17978    case 481:
17979       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
17980       p->mwi->call = NULL;
17981       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17982       pvt_set_needdestroy(p, "received 481 response");
17983       break;
17984    case 500:
17985    case 501:
17986       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
17987       p->mwi->call = NULL;
17988       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
17989       pvt_set_needdestroy(p, "received 500/501 response");
17990       break;
17991    }
17992 }
17993 
17994 /* \brief Handle SIP response in REFER transaction
17995    We've sent a REFER, now handle responses to it 
17996   */
17997 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17998 {
17999    /* If no refer structure exists, then do nothing */
18000    if (!p->refer)
18001       return;
18002 
18003    switch (resp) {
18004    case 202:   /* Transfer accepted */
18005       /* We need  to do something here */
18006       /* The transferee is now sending INVITE to target */
18007       p->refer->status = REFER_ACCEPTED;
18008       /* Now wait for next message */
18009       ast_debug(3, "Got 202 accepted on transfer\n");
18010       /* We should hang along, waiting for NOTIFY's here */
18011       break;
18012 
18013    case 401:   /* Not www-authorized on SIP method */
18014    case 407:   /* Proxy auth */
18015       if (ast_strlen_zero(p->authname)) {
18016          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
18017             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18018          pvt_set_needdestroy(p, "unable to authenticate REFER");
18019       }
18020       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
18021          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
18022          p->refer->status = REFER_NOAUTH;
18023          pvt_set_needdestroy(p, "failed to authenticat REFER");
18024       }
18025       break;
18026    case 481: /* Call leg does not exist */
18027 
18028       /* A transfer with Replaces did not work */
18029       /* OEJ: We should Set flag, cancel the REFER, go back
18030       to original call - but right now we can't */
18031       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
18032       if (p->owner)
18033          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18034       pvt_set_needdestroy(p, "received 481 response");
18035       break;
18036 
18037    case 500:   /* Server error */
18038    case 501:   /* Method not implemented */
18039       /* Return to the current call onhold */
18040       /* Status flag needed to be reset */
18041       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
18042       pvt_set_needdestroy(p, "received 500/501 response");
18043       p->refer->status = REFER_FAILED;
18044       break;
18045    case 603:   /* Transfer declined */
18046       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
18047       p->refer->status = REFER_FAILED;
18048       pvt_set_needdestroy(p, "received 603 response");
18049       break;
18050    }
18051 }
18052 
18053 /*! \brief Handle responses on REGISTER to services */
18054 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18055 {
18056    int expires, expires_ms;
18057    struct sip_registry *r;
18058    r=p->registry;
18059    
18060    switch (resp) {
18061    case 401:   /* Unauthorized */
18062       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18063          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
18064          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18065       }
18066       break;
18067    case 403:   /* Forbidden */
18068       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
18069       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
18070       r->regstate = REG_STATE_NOAUTH;
18071       pvt_set_needdestroy(p, "received 403 response");
18072       break;
18073    case 404:   /* Not found */
18074       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
18075       pvt_set_needdestroy(p, "received 404 response");
18076       if (r->call)
18077          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
18078       r->regstate = REG_STATE_REJECTED;
18079       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
18080       break;
18081    case 407:   /* Proxy auth */
18082       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
18083          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
18084          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
18085       }
18086       break;
18087    case 408:   /* Request timeout */
18088       /* Got a timeout response, so reset the counter of failed responses */
18089       if (r) {
18090          r->regattempts = 0;
18091       } else {
18092          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
18093       }
18094       break;
18095    case 423:   /* Interval too brief */
18096       r->expiry = atoi(get_header(req, "Min-Expires"));
18097       ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
18098       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
18099       if (r->call) {
18100          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
18101          pvt_set_needdestroy(p, "received 423 response");
18102       }
18103       if (r->expiry > max_expiry) {
18104          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
18105          r->expiry = r->configured_expiry;
18106          r->regstate = REG_STATE_REJECTED;
18107       } else {
18108          r->regstate = REG_STATE_UNREGISTERED;
18109          transmit_register(r, SIP_REGISTER, NULL, NULL);
18110       }
18111       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
18112       break;
18113    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
18114       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
18115       pvt_set_needdestroy(p, "received 479 response");
18116       if (r->call)
18117          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
18118       r->regstate = REG_STATE_REJECTED;
18119       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
18120       break;
18121    case 200:   /* 200 OK */
18122       if (!r) {
18123          ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
18124          pvt_set_needdestroy(p, "received erroneous 200 response");
18125          return 0;
18126       }
18127       
18128       r->regstate = REG_STATE_REGISTERED;
18129       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
18130       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
18131       r->regattempts = 0;
18132       ast_debug(1, "Registration successful\n");
18133       if (r->timeout > -1) {
18134          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
18135       }
18136       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
18137       if (r->call)
18138          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
18139       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
18140       /* Let this one hang around until we have all the responses */
18141       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18142       /* p->needdestroy = 1; */
18143       
18144       /* set us up for re-registering
18145        * figure out how long we got registered for
18146        * according to section 6.13 of RFC, contact headers override
18147        * expires headers, so check those first */
18148       expires = 0;
18149 
18150       /* XXX todo: try to save the extra call */
18151       if (!ast_strlen_zero(get_header(req, "Contact"))) {
18152          const char *contact = NULL;
18153          const char *tmptmp = NULL;
18154          int start = 0;
18155          for(;;) {
18156             contact = __get_header(req, "Contact", &start);
18157             /* this loop ensures we get a contact header about our register request */
18158             if(!ast_strlen_zero(contact)) {
18159                if( (tmptmp=strstr(contact, p->our_contact))) {
18160                   contact=tmptmp;
18161                   break;
18162                }
18163             } else
18164                break;
18165          }
18166          tmptmp = strcasestr(contact, "expires=");
18167          if (tmptmp) {
18168             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
18169                expires = 0;
18170          }
18171          
18172       }
18173       if (!expires) 
18174          expires=atoi(get_header(req, "expires"));
18175       if (!expires)
18176          expires=default_expiry;
18177       
18178       expires_ms = expires * 1000;
18179       if (expires <= EXPIRY_GUARD_LIMIT)
18180          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
18181       else
18182          expires_ms -= EXPIRY_GUARD_SECS * 1000;
18183       if (sipdebug)
18184          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
18185       
18186       r->refresh= (int) expires_ms / 1000;
18187       
18188       /* Schedule re-registration before we expire */
18189       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
18190                         registry_unref(_data,"unref in REPLACE del fail"), 
18191                         registry_unref(r,"unref in REPLACE add fail"), 
18192                         registry_addref(r,"The Addition side of REPLACE")); 
18193    }
18194    return 1;
18195 }
18196 
18197 /*! \brief Handle qualification responses (OPTIONS) */
18198 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
18199 {
18200    struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
18201    int statechanged, is_reachable, was_reachable;
18202    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
18203 
18204    /*
18205     * Compute the response time to a ping (goes in peer->lastms.)
18206     * -1 means did not respond, 0 means unknown,
18207     * 1..maxms is a valid response, >maxms means late response.
18208     */
18209    if (pingtime < 1) /* zero = unknown, so round up to 1 */
18210       pingtime = 1;
18211 
18212    /* Now determine new state and whether it has changed.
18213     * Use some helper variables to simplify the writing
18214     * of the expressions.
18215     */
18216    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
18217    is_reachable = pingtime <= peer->maxms;
18218    statechanged = peer->lastms == 0 /* yes, unknown before */
18219       || was_reachable != is_reachable;
18220 
18221    peer->lastms = pingtime;
18222    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
18223    if (statechanged) {
18224       const char *s = is_reachable ? "Reachable" : "Lagged";
18225       char str_lastms[20];
18226       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
18227 
18228       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
18229          peer->name, s, pingtime, peer->maxms);
18230       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
18231       if (sip_cfg.peer_rtupdate) {
18232          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
18233       }
18234       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
18235          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
18236          peer->name, s, pingtime);
18237       if (is_reachable && sip_cfg.regextenonqualify)
18238          register_peer_exten(peer, TRUE);
18239    }
18240 
18241    pvt_set_needdestroy(p, "got OPTIONS response");
18242 
18243    /* Try again eventually */
18244    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
18245          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
18246          sip_poke_peer_s, peer,
18247          unref_peer(_data, "removing poke peer ref"),
18248          unref_peer(peer, "removing poke peer ref"),
18249          ref_peer(peer, "adding poke peer ref"));
18250 }
18251 
18252 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
18253 static void stop_media_flows(struct sip_pvt *p)
18254 {
18255    /* Immediately stop RTP, VRTP and UDPTL as applicable */
18256    if (p->rtp)
18257       ast_rtp_stop(p->rtp);
18258    if (p->vrtp)
18259       ast_rtp_stop(p->vrtp);
18260    if (p->trtp)
18261       ast_rtp_stop(p->trtp);
18262    if (p->udptl)
18263       ast_udptl_stop(p->udptl);
18264 }
18265 
18266 /*! \brief Handle SIP response in dialogue
18267    \note only called by handle_incoming */
18268 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
18269 {
18270    struct ast_channel *owner;
18271    int sipmethod;
18272    int res = 1;
18273    const char *c = get_header(req, "Cseq");
18274    /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
18275    char *c_copy = ast_strdupa(c);
18276    /* Skip the Cseq and its subsequent spaces */
18277    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
18278 
18279    if (!msg)
18280       msg = "";
18281 
18282    sipmethod = find_sip_method(msg);
18283 
18284    owner = p->owner;
18285    if (owner) 
18286       owner->hangupcause = hangup_sip2cause(resp);
18287 
18288    if (p->socket.type == SIP_TRANSPORT_UDP) {
18289       int ack_res;
18290 
18291       /* Acknowledge whatever it is destined for */
18292       if ((resp >= 100) && (resp <= 199)) {
18293          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
18294       } else {
18295          ack_res = __sip_ack(p, seqno, 0, sipmethod);
18296       }
18297 
18298       if (ack_res == FALSE) {
18299          append_history(p, "Ignore", "Ignoring this retransmit\n");
18300          return;
18301       }
18302    }
18303 
18304    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
18305    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
18306       p->pendinginvite = 0;
18307 
18308    /* Get their tag if we haven't already */
18309    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
18310       char tag[128];
18311 
18312       gettag(req, "To", tag, sizeof(tag));
18313       ast_string_field_set(p, theirtag, tag);
18314    }
18315    /* This needs to be configurable on a channel/peer level,
18316       not mandatory for all communication. Sadly enough, NAT implementations
18317       are not so stable so we can always rely on these headers. 
18318       Temporarily disabled, while waiting for fix.
18319       Fix assigned to Rizzo :-)
18320    */
18321    /* check_via_response(p, req); */
18322 
18323    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
18324     * in response to a BYE, then we should end the current dialog
18325     * and session.  It is known that at least one phone manufacturer
18326     * potentially will send a 404 in response to a BYE, so we'll be
18327     * liberal in what we accept and end the dialog and session if we
18328     * receive any of those responses to a BYE.
18329     */
18330    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
18331       pvt_set_needdestroy(p, "received 4XX response to a BYE");
18332       return;
18333    }
18334 
18335    if (p->relatedpeer && p->method == SIP_OPTIONS) {
18336       /* We don't really care what the response is, just that it replied back. 
18337          Well, as long as it's not a 100 response...  since we might
18338          need to hang around for something more "definitive" */
18339       if (resp != 100)
18340          handle_response_peerpoke(p, resp, req);
18341    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
18342       switch(resp) {
18343       case 100:   /* 100 Trying */
18344       case 101:   /* 101 Dialog establishment */
18345       case 183:   /* 183 Session Progress */
18346       case 180:   /* 180 Ringing */
18347       case 182:   /* 182 Queued */
18348          if (sipmethod == SIP_INVITE)
18349             handle_response_invite(p, resp, rest, req, seqno);
18350          break;
18351       case 200:   /* 200 OK */
18352          p->authtries = 0; /* Reset authentication counter */
18353          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18354             /* We successfully transmitted a message 
18355                or a video update request in INFO */
18356             /* Nothing happens here - the message is inside a dialog */
18357          } else if (sipmethod == SIP_INVITE) {
18358             handle_response_invite(p, resp, rest, req, seqno);
18359          } else if (sipmethod == SIP_NOTIFY) {
18360             handle_response_notify(p, resp, rest, req, seqno);
18361          } else if (sipmethod == SIP_REGISTER) {
18362             res = handle_response_register(p, resp, rest, req, seqno);
18363          } else if (sipmethod == SIP_SUBSCRIBE) {
18364             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18365             handle_response_subscribe(p, resp, rest, req, seqno);
18366          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
18367             pvt_set_needdestroy(p, "received 200 response");
18368             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
18369          }
18370          break;
18371       case 202:   /* Transfer accepted */
18372          if (sipmethod == SIP_REFER) 
18373             handle_response_refer(p, resp, rest, req, seqno);
18374          break;
18375       case 401: /* Not www-authorized on SIP method */
18376       case 407: /* Proxy auth required */
18377          if (sipmethod == SIP_INVITE)
18378             handle_response_invite(p, resp, rest, req, seqno);
18379          else if (sipmethod == SIP_NOTIFY)
18380             handle_response_notify(p, resp, rest, req, seqno);
18381          else if (sipmethod == SIP_REFER)
18382             handle_response_refer(p, resp, rest, req, seqno);
18383          else if (sipmethod == SIP_SUBSCRIBE)
18384             handle_response_subscribe(p, resp, rest, req, seqno);
18385          else if (p->registry && sipmethod == SIP_REGISTER)
18386             res = handle_response_register(p, resp, rest, req, seqno);
18387          else if (sipmethod == SIP_BYE) {
18388             if (p->options)
18389                p->options->auth_type = resp;
18390             if (ast_strlen_zero(p->authname)) {
18391                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
18392                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
18393                pvt_set_needdestroy(p, "unable to authenticate BYE");
18394             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
18395                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18396                pvt_set_needdestroy(p, "failed to authenticate BYE");
18397             }
18398          } else {
18399             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
18400             pvt_set_needdestroy(p, "received 407 response");
18401          }
18402          break;
18403       case 403: /* Forbidden - we failed authentication */
18404          if (sipmethod == SIP_INVITE)
18405             handle_response_invite(p, resp, rest, req, seqno);
18406          else if (sipmethod == SIP_SUBSCRIBE)
18407             handle_response_subscribe(p, resp, rest, req, seqno);
18408          else if (p->registry && sipmethod == SIP_REGISTER) 
18409             res = handle_response_register(p, resp, rest, req, seqno);
18410          else {
18411             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
18412             pvt_set_needdestroy(p, "received 403 response");
18413          }
18414          break;
18415       case 404: /* Not found */
18416          if (p->registry && sipmethod == SIP_REGISTER)
18417             res = handle_response_register(p, resp, rest, req, seqno);
18418          else if (sipmethod == SIP_INVITE)
18419             handle_response_invite(p, resp, rest, req, seqno);
18420          else if (sipmethod == SIP_SUBSCRIBE)
18421             handle_response_subscribe(p, resp, rest, req, seqno);
18422          else if (owner)
18423             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18424          break;
18425       case 423: /* Interval too brief */
18426          if (sipmethod == SIP_REGISTER)
18427             res = handle_response_register(p, resp, rest, req, seqno);
18428          break;
18429       case 408: /* Request timeout - terminate dialog */
18430          if (sipmethod == SIP_INVITE)
18431             handle_response_invite(p, resp, rest, req, seqno);
18432          else if (sipmethod == SIP_REGISTER) 
18433             res = handle_response_register(p, resp, rest, req, seqno);
18434          else if (sipmethod == SIP_BYE) {
18435             pvt_set_needdestroy(p, "received 408 response");
18436             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
18437          } else {
18438             if (owner)
18439                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18440             pvt_set_needdestroy(p, "received 408 response");
18441          }
18442          break;
18443 
18444       case 422: /* Session-Timers: Session Interval Too Small */
18445          if (sipmethod == SIP_INVITE) {
18446             handle_response_invite(p, resp, rest, req, seqno);
18447          }
18448          break;
18449 
18450       case 481: /* Call leg does not exist */
18451          if (sipmethod == SIP_INVITE) {
18452             handle_response_invite(p, resp, rest, req, seqno);
18453          } else if (sipmethod == SIP_REFER) {
18454             handle_response_refer(p, resp, rest, req, seqno);
18455          } else if (sipmethod == SIP_SUBSCRIBE) {
18456             handle_response_subscribe(p, resp, rest, req, seqno);
18457          } else if (sipmethod == SIP_BYE) {
18458             /* The other side has no transaction to bye,
18459             just assume it's all right then */
18460             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18461          } else if (sipmethod == SIP_CANCEL) {
18462             /* The other side has no transaction to cancel,
18463             just assume it's all right then */
18464             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18465          } else {
18466             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
18467             /* Guessing that this is not an important request */
18468          }
18469          break;
18470       case 487:
18471          if (sipmethod == SIP_INVITE)
18472             handle_response_invite(p, resp, rest, req, seqno);
18473          break;
18474       case 415: /* Unsupported media type */
18475       case 488: /* Not acceptable here - codec error */
18476       case 606: /* Not Acceptable */
18477          if (sipmethod == SIP_INVITE)
18478             handle_response_invite(p, resp, rest, req, seqno);
18479          break;
18480       case 491: /* Pending */
18481          if (sipmethod == SIP_INVITE)
18482             handle_response_invite(p, resp, rest, req, seqno);
18483          else {
18484             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
18485             pvt_set_needdestroy(p, "received 491 response");
18486          }
18487          break;
18488       case 501: /* Not Implemented */
18489          if (sipmethod == SIP_INVITE)
18490             handle_response_invite(p, resp, rest, req, seqno);
18491          else if (sipmethod == SIP_REFER)
18492             handle_response_refer(p, resp, rest, req, seqno);
18493          else
18494             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
18495          break;
18496       case 603:   /* Declined transfer */
18497          if (sipmethod == SIP_REFER) {
18498             handle_response_refer(p, resp, rest, req, seqno);
18499             break;
18500          }
18501          /* Fallthrough */
18502       default:
18503          if ((resp >= 300) && (resp < 700)) {
18504             /* Fatal response */
18505             if ((resp != 487))
18506                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18507    
18508             if (sipmethod == SIP_INVITE)
18509                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
18510 
18511             /* XXX Locking issues?? XXX */
18512             switch(resp) {
18513             case 300: /* Multiple Choices */
18514             case 301: /* Moved permanently */
18515             case 302: /* Moved temporarily */
18516             case 305: /* Use Proxy */
18517                parse_moved_contact(p, req);
18518                /* Fall through */
18519             case 486: /* Busy here */
18520             case 600: /* Busy everywhere */
18521             case 603: /* Decline */
18522                if (p->owner)
18523                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
18524                break;
18525             case 482: /*!
18526                \note SIP is incapable of performing a hairpin call, which
18527                is yet another failure of not having a layer 2 (again, YAY
18528                 IETF for thinking ahead).  So we treat this as a call
18529                 forward and hope we end up at the right place... */
18530                ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
18531                if (p->owner)
18532                   ast_string_field_build(p->owner, call_forward,
18533                                "Local/%s@%s", p->username, p->context);
18534                /* Fall through */
18535             case 480: /* Temporarily Unavailable */
18536             case 404: /* Not Found */
18537             case 410: /* Gone */
18538             case 400: /* Bad Request */
18539             case 500: /* Server error */
18540                if (sipmethod == SIP_REFER) {
18541                   handle_response_refer(p, resp, rest, req, seqno);
18542                   break;
18543                } else if (sipmethod == SIP_SUBSCRIBE) {
18544                   handle_response_subscribe(p, resp, rest, req, seqno);
18545                   break;
18546                }
18547                /* Fall through */
18548             case 502: /* Bad gateway */
18549             case 503: /* Service Unavailable */
18550             case 504: /* Server Timeout */
18551                if (owner)
18552                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
18553                break;
18554             default:
18555                /* Send hangup */ 
18556                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
18557                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
18558                break;
18559             }
18560             /* ACK on invite */
18561             if (sipmethod == SIP_INVITE) 
18562                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
18563             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
18564                sip_alreadygone(p);
18565             if (!p->owner) {
18566                pvt_set_needdestroy(p, "transaction completed");
18567             }
18568          } else if ((resp >= 100) && (resp < 200)) {
18569             if (sipmethod == SIP_INVITE) {
18570                if (!req->ignore && sip_cancel_destroy(p))
18571                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18572                if (find_sdp(req))
18573                   process_sdp(p, req, SDP_T38_NONE);
18574                if (p->owner) {
18575                   /* Queue a progress frame */
18576                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
18577                }
18578             }
18579          } else
18580             ast_log(LOG_NOTICE, "Dont know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_inet_ntoa(p->sa.sin_addr));
18581       }
18582    } else { 
18583       /* Responses to OUTGOING SIP requests on INCOMING calls 
18584          get handled here. As well as out-of-call message responses */
18585       if (req->debug)
18586          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
18587 
18588       if (sipmethod == SIP_INVITE && resp == 200) {
18589          /* Tags in early session is replaced by the tag in 200 OK, which is 
18590          the final reply to our INVITE */
18591          char tag[128];
18592 
18593          gettag(req, "To", tag, sizeof(tag));
18594          ast_string_field_set(p, theirtag, tag);
18595       }
18596 
18597       switch(resp) {
18598       case 200:
18599          if (sipmethod == SIP_INVITE) {
18600             handle_response_invite(p, resp, rest, req, seqno);
18601          } else if (sipmethod == SIP_CANCEL) {
18602             ast_debug(1, "Got 200 OK on CANCEL\n");
18603 
18604             /* Wait for 487, then destroy */
18605          } else if (sipmethod == SIP_NOTIFY) {
18606             /* They got the notify, this is the end */
18607             if (p->owner) {
18608                if (p->refer) {
18609                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
18610                } else
18611                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
18612                /* ast_queue_hangup(p->owner); Disabled */
18613             } else {
18614                if (!p->subscribed && !p->refer) {
18615                   pvt_set_needdestroy(p, "transaction completed");
18616                }
18617                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
18618                   /* Ready to send the next state we have on queue */
18619                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
18620                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
18621                }
18622             }
18623          } else if (sipmethod == SIP_BYE) {
18624             pvt_set_needdestroy(p, "transaction completed");
18625          } else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
18626             /* We successfully transmitted a message or
18627                a video update request in INFO */
18628             ;
18629          }
18630          break;
18631       case 202:   /* Transfer accepted */
18632          if (sipmethod == SIP_REFER) 
18633             handle_response_refer(p, resp, rest, req, seqno);
18634          break;
18635       case 401:   /* www-auth */
18636       case 407:
18637          if (sipmethod == SIP_REFER)
18638             handle_response_refer(p, resp, rest, req, seqno);
18639          else if (sipmethod == SIP_INVITE) 
18640             handle_response_invite(p, resp, rest, req, seqno);
18641          else if (sipmethod == SIP_BYE) {
18642             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
18643                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
18644                pvt_set_needdestroy(p, "failed to authenticate BYE");
18645             }
18646          }
18647          break;
18648       case 481:   /* Call leg does not exist */
18649          if (sipmethod == SIP_INVITE) {
18650             /* Re-invite failed */
18651             handle_response_invite(p, resp, rest, req, seqno);
18652          } else if (sipmethod == SIP_BYE) {
18653             pvt_set_needdestroy(p, "received 481 response");
18654          } else if (sipdebug) {
18655             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
18656          }
18657          break;
18658       case 501: /* Not Implemented */
18659          if (sipmethod == SIP_INVITE) 
18660             handle_response_invite(p, resp, rest, req, seqno);
18661          else if (sipmethod == SIP_REFER) 
18662             handle_response_refer(p, resp, rest, req, seqno);
18663          break;
18664       case 603:   /* Declined transfer */
18665          if (sipmethod == SIP_REFER) {
18666             handle_response_refer(p, resp, rest, req, seqno);
18667             break;
18668          }
18669          /* Fallthrough */
18670       default: /* Errors without handlers */
18671          if ((resp >= 100) && (resp < 200)) {
18672             if (sipmethod == SIP_INVITE) {   /* re-invite */
18673                if (!req->ignore && sip_cancel_destroy(p))
18674                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18675             }
18676          }
18677          if ((resp >= 300) && (resp < 700)) {
18678             if ((resp != 487))
18679                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
18680             switch(resp) {
18681             case 415: /* Unsupported media type */
18682             case 488: /* Not acceptable here - codec error */
18683             case 603: /* Decline */
18684             case 500: /* Server error */
18685             case 502: /* Bad gateway */
18686             case 503: /* Service Unavailable */
18687             case 504: /* Server timeout */
18688 
18689                /* re-invite failed */
18690                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
18691                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18692                break;
18693             }
18694          }
18695          break;
18696       }
18697    }
18698 }
18699 
18700 
18701 /*! \brief Park SIP call support function 
18702    Starts in a new thread, then parks the call
18703    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
18704       audio can't be heard before hangup
18705 */
18706 static void *sip_park_thread(void *stuff)
18707 {
18708    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
18709    struct sip_dual *d;
18710    struct sip_request req = {0,};
18711    int ext;
18712    int res;
18713 
18714    d = stuff;
18715    transferee = d->chan1;
18716    transferer = d->chan2;
18717    copy_request(&req, &d->req);
18718 
18719    if (!transferee || !transferer) {
18720       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
18721       if (d->req.data)
18722          ast_free(d->req.data);
18723       free(d);
18724       return NULL;
18725    }
18726    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
18727 
18728    ast_channel_lock(transferee);
18729    if (ast_do_masquerade(transferee)) {
18730       ast_log(LOG_WARNING, "Masquerade failed.\n");
18731       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
18732       ast_channel_unlock(transferee);
18733       if (d->req.data)
18734          ast_free(d->req.data);
18735       free(d);
18736       return NULL;
18737    } 
18738    ast_channel_unlock(transferee);
18739 
18740    res = ast_park_call(transferee, transferer, 0, &ext);
18741    
18742 
18743 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
18744    if (!res) {
18745       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
18746    } else {
18747       /* Then tell the transferer what happened */
18748       sprintf(buf, "Call parked on extension '%d'", ext);
18749       transmit_message_with_text(transferer->tech_pvt, buf);
18750    }
18751 #endif
18752 
18753    /* Any way back to the current call??? */
18754    /* Transmit response to the REFER request */
18755    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
18756    if (!res)   {
18757       /* Transfer succeeded */
18758       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
18759       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
18760       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
18761       ast_hangup(transferer); /* This will cause a BYE */
18762       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
18763    } else {
18764       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
18765       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
18766       ast_debug(1, "SIP Call parked failed \n");
18767       /* Do not hangup call */
18768    }
18769    if (d->req.data)
18770       ast_free(d->req.data);
18771    free(d);
18772    return NULL;
18773 }
18774 
18775 /*! \brief Park a call using the subsystem in res_features.c 
18776    This is executed in a separate thread
18777 */
18778 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
18779 {
18780    struct sip_dual *d;
18781    struct ast_channel *transferee, *transferer;
18782       /* Chan2m: The transferer, chan1m: The transferee */
18783    pthread_t th;
18784 
18785    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
18786    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
18787    if ((!transferer) || (!transferee)) {
18788       if (transferee) {
18789          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18790          ast_hangup(transferee);
18791       }
18792       if (transferer) {
18793          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18794          ast_hangup(transferer);
18795       }
18796       return -1;
18797    }
18798 
18799    /* Make formats okay */
18800    transferee->readformat = chan1->readformat;
18801    transferee->writeformat = chan1->writeformat;
18802 
18803    /* Prepare for taking over the channel */
18804    ast_channel_masquerade(transferee, chan1);
18805 
18806    /* Setup the extensions and such */
18807    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
18808    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
18809    transferee->priority = chan1->priority;
18810       
18811    /* We make a clone of the peer channel too, so we can play
18812       back the announcement */
18813 
18814    /* Make formats okay */
18815    transferer->readformat = chan2->readformat;
18816    transferer->writeformat = chan2->writeformat;
18817    if (!ast_strlen_zero(chan2->parkinglot))
18818       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
18819 
18820    /* Prepare for taking over the channel.  Go ahead and grab this channel
18821     * lock here to avoid a deadlock with callbacks into the channel driver
18822     * that hold the channel lock and want the pvt lock.  */
18823    while (ast_channel_trylock(chan2)) {
18824       struct sip_pvt *pvt = chan2->tech_pvt;
18825       sip_pvt_unlock(pvt);
18826       usleep(1);
18827       sip_pvt_lock(pvt);
18828    }
18829    ast_channel_masquerade(transferer, chan2);
18830    ast_channel_unlock(chan2);
18831 
18832    /* Setup the extensions and such */
18833    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
18834    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
18835    transferer->priority = chan2->priority;
18836 
18837    ast_channel_lock(transferer);
18838    if (ast_do_masquerade(transferer)) {
18839       ast_log(LOG_WARNING, "Masquerade failed :(\n");
18840       ast_channel_unlock(transferer);
18841       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18842       ast_hangup(transferer);
18843       return -1;
18844    }
18845    ast_channel_unlock(transferer);
18846    if (!transferer || !transferee) {
18847       if (!transferer) { 
18848          ast_debug(1, "No transferer channel, giving up parking\n");
18849       }
18850       if (!transferee) {
18851          ast_debug(1, "No transferee channel, giving up parking\n");
18852       }
18853       return -1;
18854    }
18855    if ((d = ast_calloc(1, sizeof(*d)))) {
18856 
18857       /* Save original request for followup */
18858       copy_request(&d->req, req);
18859       d->chan1 = transferee;  /* Transferee */
18860       d->chan2 = transferer;  /* Transferer */
18861       d->seqno = seqno;
18862       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18863          /* Could not start thread */
18864          if (d->req.data)
18865             ast_free(d->req.data);
18866          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
18867                   by sip_park_thread() */
18868          return 0;
18869       }
18870    } 
18871    return -1;
18872 }
18873 
18874 /*! \brief Turn off generator data 
18875    XXX Does this function belong in the SIP channel?
18876 */
18877 static void ast_quiet_chan(struct ast_channel *chan) 
18878 {
18879    if (chan && chan->_state == AST_STATE_UP) {
18880       if (ast_test_flag(chan, AST_FLAG_MOH))
18881          ast_moh_stop(chan);
18882       else if (chan->generatordata)
18883          ast_deactivate_generator(chan);
18884    }
18885 }
18886 
18887 /*! \brief Attempt transfer of SIP call 
18888    This fix for attended transfers on a local PBX */
18889 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18890 {
18891    int res = 0;
18892    struct ast_channel *peera = NULL,   
18893       *peerb = NULL,
18894       *peerc = NULL,
18895       *peerd = NULL;
18896 
18897 
18898    /* We will try to connect the transferee with the target and hangup
18899       all channels to the transferer */   
18900    ast_debug(4, "Sip transfer:--------------------\n");
18901    if (transferer->chan1)
18902       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18903    else
18904       ast_debug(4, "-- No transferer first channel - odd??? \n");
18905    if (target->chan1)
18906       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
18907    else
18908       ast_debug(4, "-- No target first channel ---\n");
18909    if (transferer->chan2)
18910       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
18911    else
18912       ast_debug(4, "-- No bridged call to transferee\n");
18913    if (target->chan2)
18914       ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
18915    else
18916       ast_debug(4, "-- No target second channel ---\n");
18917    ast_debug(4, "-- END Sip transfer:--------------------\n");
18918    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
18919       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
18920       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
18921       peerc = transferer->chan2; /* Asterisk to Transferee */
18922       peerd = target->chan2;     /* Asterisk to Target */
18923       ast_debug(3, "SIP transfer: Four channels to handle\n");
18924    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
18925       peera = target->chan1;     /* Transferer to PBX -> target channel */
18926       peerb = transferer->chan1; /* Transferer to IVR*/
18927       peerc = target->chan2;     /* Asterisk to Target */
18928       peerd = transferer->chan2; /* Nothing */
18929       ast_debug(3, "SIP transfer: Three channels to handle\n");
18930    }
18931 
18932    if (peera && peerb && peerc && (peerb != peerc)) {
18933       ast_quiet_chan(peera);     /* Stop generators */
18934       ast_quiet_chan(peerb);  
18935       ast_quiet_chan(peerc);
18936       if (peerd)
18937          ast_quiet_chan(peerd);
18938 
18939       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
18940       if (ast_channel_masquerade(peerb, peerc)) {
18941          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
18942          res = -1;
18943       } else
18944          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
18945       return res;
18946    } else {
18947       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
18948       if (transferer->chan1)
18949          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
18950       if (target->chan1)
18951          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
18952       return -1;
18953    }
18954    return 0;
18955 }
18956 
18957 /*! \brief Get tag from packet 
18958  *
18959  * \return Returns the pointer to the provided tag buffer,
18960  *         or NULL if the tag was not found.
18961  */
18962 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
18963 {
18964    const char *thetag;
18965 
18966    if (!tagbuf)
18967       return NULL;
18968    tagbuf[0] = '\0';    /* reset the buffer */
18969    thetag = get_header(req, header);
18970    thetag = strcasestr(thetag, ";tag=");
18971    if (thetag) {
18972       thetag += 5;
18973       ast_copy_string(tagbuf, thetag, tagbufsize);
18974       return strsep(&tagbuf, ";");
18975    }
18976    return NULL;
18977 }
18978 
18979 /*! \brief Handle incoming notifications */
18980 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
18981 {
18982    /* This is mostly a skeleton for future improvements */
18983    /* Mostly created to return proper answers on notifications on outbound REFER's */
18984    int res = 0;
18985    const char *event = get_header(req, "Event");
18986    char *eventid = NULL;
18987    char *sep;
18988 
18989    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
18990       *sep++ = '\0';
18991       eventid = sep;
18992    }
18993    
18994    if (sipdebug)
18995       ast_debug(2, "Got NOTIFY Event: %s\n", event);
18996 
18997    if (!strcmp(event, "refer")) {
18998       /* Save nesting depth for now, since there might be other events we will
18999          support in the future */
19000 
19001       /* Handle REFER notifications */
19002 
19003       char buf[1024];
19004       char *cmd, *code;
19005       int respcode;
19006       int success = TRUE;
19007 
19008       /* EventID for each transfer... EventID is basically the REFER cseq 
19009 
19010        We are getting notifications on a call that we transfered
19011        We should hangup when we are getting a 200 OK in a sipfrag
19012        Check if we have an owner of this event */
19013       
19014       /* Check the content type */
19015       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
19016          /* We need a sipfrag */
19017          transmit_response(p, "400 Bad request", req);
19018          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19019          return -1;
19020       }
19021 
19022       /* Get the text of the attachment */
19023       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
19024          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
19025          transmit_response(p, "400 Bad request", req);
19026          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19027          return -1;
19028       }
19029 
19030       /*
19031       From the RFC...
19032       A minimal, but complete, implementation can respond with a single
19033       NOTIFY containing either the body:
19034          SIP/2.0 100 Trying
19035       
19036       if the subscription is pending, the body:
19037          SIP/2.0 200 OK
19038       if the reference was successful, the body:
19039          SIP/2.0 503 Service Unavailable
19040       if the reference failed, or the body:
19041          SIP/2.0 603 Declined
19042 
19043       if the REFER request was accepted before approval to follow the
19044       reference could be obtained and that approval was subsequently denied
19045       (see Section 2.4.7).
19046       
19047       If there are several REFERs in the same dialog, we need to
19048       match the ID of the event header...
19049       */
19050       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
19051       cmd = ast_skip_blanks(buf);
19052       code = cmd;
19053       /* We are at SIP/2.0 */
19054       while(*code && (*code > 32)) {   /* Search white space */
19055          code++;
19056       }
19057       *code++ = '\0';
19058       code = ast_skip_blanks(code);
19059       sep = code;
19060       sep++;
19061       while(*sep && (*sep > 32)) {  /* Search white space */
19062          sep++;
19063       }
19064       *sep++ = '\0';       /* Response string */
19065       respcode = atoi(code);
19066       switch (respcode) {
19067       case 100:   /* Trying: */
19068       case 101:   /* dialog establishment */
19069          /* Don't do anything yet */
19070          break;
19071       case 183:   /* Ringing: */
19072          /* Don't do anything yet */
19073          break;
19074       case 200:   /* OK: The new call is up, hangup this call */
19075          /* Hangup the call that we are replacing */
19076          break;
19077       case 301: /* Moved permenantly */
19078       case 302: /* Moved temporarily */
19079          /* Do we get the header in the packet in this case? */
19080          success = FALSE;
19081          break;
19082       case 503:   /* Service Unavailable: The new call failed */
19083             /* Cancel transfer, continue the call */
19084          success = FALSE;
19085          break;
19086       case 603:   /* Declined: Not accepted */
19087             /* Cancel transfer, continue the current call */
19088          success = FALSE;
19089          break;
19090       }
19091       if (!success) {
19092          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
19093       }
19094       
19095       /* Confirm that we received this packet */
19096       transmit_response(p, "200 OK", req);
19097    } else if (p->mwi && !strcmp(event, "message-summary")) {
19098       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
19099 
19100       if (!ast_strlen_zero(c)) {
19101          char *old = strsep(&c, " ");
19102          char *new = strsep(&old, "/");
19103          struct ast_event *event;
19104 
19105          if ((event = ast_event_new(AST_EVENT_MWI,
19106                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mwi->mailbox,
19107                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
19108                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
19109                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
19110                      AST_EVENT_IE_END))) {
19111             ast_event_queue_and_cache(event);
19112          }
19113       }
19114 
19115       transmit_response(p, "200 OK", req);
19116    } else if (!strcmp(event, "keep-alive")) {
19117        /* Used by Sipura/Linksys for NAT pinhole,
19118         * just confirm that we recieved the packet. */
19119       transmit_response(p, "200 OK", req);
19120    } else {
19121       /* We don't understand this event. */
19122       transmit_response(p, "489 Bad event", req);
19123       res = -1;
19124    }
19125 
19126    if (!p->lastinvite)
19127       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19128 
19129    return res;
19130 }
19131 
19132 /*! \brief Handle incoming OPTIONS request 
19133    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
19134 */
19135 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
19136 {
19137    int res;
19138 
19139    /*! XXX get_destination assumes we're already authenticated. This means that a request from
19140       a known device (peer) will end up in the wrong context if this is out-of-dialog.
19141       However, we want to handle OPTIONS as light as possible, so we might want to have
19142       a configuration option whether we care or not. Some devices use this for testing
19143       capabilities, which means that we need to match device to answer with proper 
19144       capabilities (including SDP).
19145       \todo Fix handle_request_options device handling with optional authentication
19146          (this needs to be fixed in 1.4 as well)
19147    */
19148 
19149    if (p->lastinvite) {
19150       /* if this is a request in an active dialog, just confirm that the dialog exists. */
19151       transmit_response_with_allow(p, "200 OK", req, 0);
19152       return 0;
19153    }
19154 
19155    res = get_destination(p, req);
19156    build_contact(p);
19157 
19158    if (ast_strlen_zero(p->context))
19159       ast_string_field_set(p, context, sip_cfg.default_context);
19160 
19161    if (ast_shutting_down())
19162       transmit_response_with_allow(p, "503 Unavailable", req, 0);
19163    else if (res < 0)
19164       transmit_response_with_allow(p, "404 Not Found", req, 0);
19165    else 
19166       transmit_response_with_allow(p, "200 OK", req, 0);
19167 
19168    /* Destroy if this OPTIONS was the opening request, but not if
19169       it's in the middle of a normal call flow. */
19170    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19171 
19172    return res;
19173 }
19174 
19175 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
19176     meaning a target pickup or an attended transfer.
19177     Used only once.
19178    XXX 'ignore' is unused.
19179 
19180    \note this function is called by handle_request_invite(). Four locks
19181    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
19182    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
19183  */
19184 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
19185 {
19186    int earlyreplace = 0;
19187    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
19188    struct ast_channel *c = p->owner;   /* Our incoming call */
19189    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
19190    struct ast_channel *targetcall;     /* The bridge to the take-over target */
19191 
19192    struct ast_channel *test;
19193 
19194    /* Check if we're in ring state */
19195    if (replacecall->_state == AST_STATE_RING)
19196       earlyreplace = 1;
19197 
19198    /* Check if we have a bridge */
19199    if (!(targetcall = ast_bridged_channel(replacecall))) {
19200       /* We have no bridge */
19201       if (!earlyreplace) {
19202          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
19203          oneleggedreplace = 1;
19204       }
19205    } 
19206    if (targetcall && targetcall->_state == AST_STATE_RINGING)
19207       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
19208 
19209    if (targetcall) 
19210       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
19211    else
19212       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
19213 
19214    if (req->ignore) {
19215       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
19216       /* We should answer something here. If we are here, the
19217          call we are replacing exists, so an accepted 
19218          can't harm */
19219       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19220       /* Do something more clever here */
19221       if (c) {
19222          *nounlock = 1;
19223          ast_channel_unlock(c);
19224       }
19225       ast_channel_unlock(replacecall);
19226       sip_pvt_unlock(p->refer->refer_call);
19227       return 1;
19228    } 
19229    if (!c) {
19230       /* What to do if no channel ??? */
19231       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
19232       transmit_response_reliable(p, "503 Service Unavailable", req);
19233       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
19234       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19235       ast_channel_unlock(replacecall);
19236       sip_pvt_unlock(p->refer->refer_call);
19237       return 1;
19238    }
19239    append_history(p, "Xfer", "INVITE/Replace received");
19240    /* We have three channels to play with
19241       channel c: New incoming call
19242       targetcall: Call from PBX to target
19243       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
19244       replacecall: The owner of the previous
19245       We need to masq C into refer_call to connect to 
19246       targetcall;
19247       If we are talking to internal audio stream, target call is null.
19248    */
19249 
19250    /* Fake call progress */
19251    transmit_response(p, "100 Trying", req);
19252    ast_setstate(c, AST_STATE_RING);
19253 
19254    /* Masquerade the new call into the referred call to connect to target call 
19255       Targetcall is not touched by the masq */
19256 
19257    /* Answer the incoming call and set channel to UP state */
19258    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
19259       
19260    ast_setstate(c, AST_STATE_UP);
19261    
19262    /* Stop music on hold and other generators */
19263    ast_quiet_chan(replacecall);
19264    ast_quiet_chan(targetcall);
19265    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
19266 
19267    /* Make sure that the masq does not free our PVT for the old call */
19268    if (! earlyreplace && ! oneleggedreplace )
19269       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
19270 
19271    /* Prepare the masquerade - if this does not happen, we will be gone */
19272    if(ast_channel_masquerade(replacecall, c))
19273       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
19274    else
19275       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
19276 
19277    /* C should now be in place of replacecall */
19278    if (ast_do_masquerade(replacecall)) {
19279       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
19280    }
19281 
19282    if (earlyreplace || oneleggedreplace ) {
19283       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
19284    }
19285 
19286    ast_setstate(c, AST_STATE_DOWN);
19287    ast_debug(4, "After transfer:----------------------------\n");
19288    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
19289    if (replacecall)
19290       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
19291    if (p->owner) {
19292       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
19293       test = ast_bridged_channel(p->owner);
19294       if (test)
19295          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
19296       else
19297          ast_debug(4, " -- No call bridged to C->owner \n");
19298    } else 
19299       ast_debug(4, " -- No channel yet \n");
19300    ast_debug(4, "End After transfer:----------------------------\n");
19301 
19302    /* unlock sip pvt and owner so hangup can do its thing */
19303    ast_channel_unlock(replacecall);
19304    ast_channel_unlock(c);
19305    sip_pvt_unlock(p->refer->refer_call);
19306    sip_pvt_unlock(p);
19307    *nounlock = 1;
19308 
19309    /* The call should be down with no ast_channel, so hang it up */
19310    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
19311    ast_hangup(c);
19312    sip_pvt_lock(p); /* lock PVT structure again after hangup */
19313 
19314    return 0;
19315 }
19316 
19317 /*! \brief helper routine for sip_uri_cmp
19318  *
19319  * This takes the parameters from two SIP URIs and determines
19320  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
19321  * 1. If a parameter appears in both URIs, then they must have the same value
19322  *    in order for the URIs to match
19323  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
19324  *    URI must also have that parameter and must have the same value
19325  *    in order for the URIs to match
19326  * 3. All other headers appearing in only one URI are not considered when
19327  *    determining if URIs match
19328  *
19329  * \param input1 Parameters from URI 1
19330  * \param input2 Parameters from URI 2
19331  * \return Return 0 if the URIs' parameters match, 1 if they do not
19332  */
19333 static int sip_uri_params_cmp(const char *input1, const char *input2) 
19334 {
19335    char *params1 = NULL;
19336    char *params2 = NULL;
19337    char *pos1;
19338    char *pos2;
19339    int zerolength1 = 0;
19340    int zerolength2 = 0;
19341    int maddrmatch = 0;
19342    int ttlmatch = 0;
19343    int usermatch = 0;
19344    int methodmatch = 0;
19345 
19346    if (ast_strlen_zero(input1)) {
19347       zerolength1 = 1;
19348    } else {
19349       params1 = ast_strdupa(input1);
19350    }
19351    if (ast_strlen_zero(input2)) {
19352       zerolength2 = 1;
19353    } else {
19354       params2 = ast_strdupa(input2);
19355    }
19356 
19357    /*Quick optimization. If both params are zero-length, then
19358     * they match
19359     */
19360    if (zerolength1 && zerolength2) {
19361       return 0;
19362    }
19363 
19364    pos1 = params1;
19365    while (!ast_strlen_zero(pos1)) {
19366       char *name1 = pos1;
19367       char *value1 = strchr(pos1, '=');
19368       char *semicolon1 = strchr(pos1, ';');
19369       int matched = 0;
19370       if (semicolon1) {
19371          *semicolon1++ = '\0';
19372       }
19373       if (!value1) {
19374          goto fail;
19375       }
19376       *value1++ = '\0';
19377       /* Checkpoint reached. We have the name and value parsed for param1 
19378        * We have to duplicate params2 each time through the second loop
19379        * or else we can't search and replace the semicolons with \0 each
19380        * time
19381        */
19382       pos2 = ast_strdupa(params2);
19383       while (!ast_strlen_zero(pos2)) {
19384          char *name2 = pos2;
19385          char *value2 = strchr(pos2, '=');
19386          char *semicolon2 = strchr(pos2, ';');
19387          if (semicolon2) {
19388             *semicolon2++ = '\0';
19389          }
19390          if (!value2) {
19391             goto fail;
19392          }
19393          *value2++ = '\0';
19394          if (!strcasecmp(name1, name2)) {
19395             if (strcasecmp(value1, value2)) {
19396                goto fail;
19397             } else {
19398                matched = 1;
19399                break;
19400             }
19401          }
19402          pos2 = semicolon2;
19403       }
19404       /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
19405       if (!strcasecmp(name1, "maddr")) {
19406          if (matched) {
19407             maddrmatch = 1;
19408          } else {
19409             goto fail;
19410          }
19411       } else if (!strcasecmp(name1, "ttl")) {
19412          if (matched) {
19413             ttlmatch = 1;
19414          } else {
19415             goto fail;
19416          }
19417       } else if (!strcasecmp(name1, "user")) {
19418          if (matched) {
19419             usermatch = 1;
19420          } else {
19421             goto fail;
19422          }
19423       } else if (!strcasecmp(name1, "method")) {
19424          if (matched) {
19425             methodmatch = 1;
19426          } else {
19427             goto fail;
19428          }
19429       }
19430       pos1 = semicolon1;
19431    }
19432 
19433    /* We've made it out of that horrible O(m*n) construct and there are no
19434     * failures yet. We're not done yet, though, because params2 could have
19435     * an maddr, ttl, user, or method header and params1 did not.
19436     */
19437    pos2 = params2;
19438    while (!ast_strlen_zero(pos2)) {
19439       char *name2 = pos2;
19440       char *value2 = strchr(pos2, '=');
19441       char *semicolon2 = strchr(pos2, ';');
19442       if (semicolon2) {
19443          *semicolon2++ = '\0';
19444       }
19445       if (!value2) {
19446          goto fail;
19447       }
19448       *value2++ = '\0';
19449       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
19450             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
19451             (!strcasecmp(name2, "user") && !usermatch) ||
19452             (!strcasecmp(name2, "method") && !methodmatch)) {
19453          goto fail;
19454       }
19455    }
19456    return 0;
19457 
19458 fail:
19459    return 1;
19460 }
19461 
19462 /*! \brief helper routine for sip_uri_cmp
19463  *
19464  * This takes the "headers" from two SIP URIs and determines
19465  * if the URIs match. The rules for headers is simple. If a header
19466  * appears in one URI, then it must also appear in the other URI. The
19467  * order in which the headers appear does not matter.
19468  *
19469  * \param input1 Headers from URI 1
19470  * \param input2 Headers from URI 2
19471  * \return Return 0 if the URIs' headers match, 1 if they do not
19472  */
19473 static int sip_uri_headers_cmp(const char *input1, const char *input2)
19474 {
19475    char *headers1 = NULL;
19476    char *headers2 = NULL;
19477    int zerolength1 = 0;
19478    int zerolength2 = 0;
19479    int different = 0;
19480    char *header1;
19481 
19482    if (ast_strlen_zero(input1)) {
19483       zerolength1 = 1;
19484    } else {
19485       headers1 = ast_strdupa(input1);
19486    }
19487    
19488    if (ast_strlen_zero(input2)) {
19489       zerolength2 = 1;
19490    } else {
19491       headers2 = ast_strdupa(input2);
19492    }
19493 
19494    if ((zerolength1 && !zerolength2) ||
19495          (zerolength2 && !zerolength1))
19496       return 1;
19497 
19498    if (zerolength1 && zerolength2)
19499       return 0;
19500 
19501    /* At this point, we can definitively state that both inputs are
19502     * not zero-length. First, one more optimization. If the length
19503     * of the headers is not equal, then we definitely have no match
19504     */
19505    if (strlen(headers1) != strlen(headers2)) {
19506       return 1;
19507    }
19508 
19509    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
19510       if (!strcasestr(headers2, header1)) {
19511          different = 1;
19512          break;
19513       }
19514    }
19515 
19516    return different;
19517 }
19518 
19519 static int sip_uri_cmp(const char *input1, const char *input2)
19520 {
19521    char *uri1 = ast_strdupa(input1);
19522    char *uri2 = ast_strdupa(input2);
19523    char *host1;
19524    char *host2;
19525    char *params1;
19526    char *params2;
19527    char *headers1;
19528    char *headers2;
19529 
19530    /* Strip off "sip:" from the URI. We know this is present
19531     * because it was checked back in parse_request()
19532     */
19533    strsep(&uri1, ":");
19534    strsep(&uri2, ":");
19535 
19536    if ((host1 = strchr(uri1, '@'))) {
19537       *host1++ = '\0';
19538    }
19539    if ((host2 = strchr(uri2, '@'))) {
19540       *host2++ = '\0';
19541    }
19542 
19543    /* Check for mismatched username and passwords. This is the
19544     * only case-sensitive comparison of a SIP URI
19545     */
19546    if ((host1 && !host2) ||
19547          (host2 && !host1) ||
19548          (host1 && host2 && strcmp(uri1, uri2))) {
19549       return 1;
19550    }
19551 
19552    if (!host1)
19553       host1 = uri1;
19554    if (!host2)
19555       host2 = uri2;
19556 
19557    /* Strip off the parameters and headers so we can compare
19558     * host and port
19559     */
19560 
19561    if ((params1 = strchr(host1, ';'))) {
19562       *params1++ = '\0';
19563    }
19564    if ((params2 = strchr(host2, ';'))) {
19565       *params2++ = '\0';
19566    }
19567 
19568    /* Headers come after parameters, but there may be headers without
19569     * parameters, thus the S_OR
19570     */
19571    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
19572       *headers1++ = '\0';
19573    }
19574    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
19575       *headers2++ = '\0';
19576    }
19577 
19578    /* Now the host/port are properly isolated. We can get by with a string comparison
19579     * because the SIP URI checking rules have some interesting exceptions that make
19580     * this possible. I will note 2 in particular
19581     * 1. hostnames which resolve to the same IP address as well as a hostname and its
19582     *    IP address are not considered a match with SIP URI's.
19583     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
19584     *    This includes if one URI explicitly contains port 5060 and the other implies it
19585     *    by not having a port specified.
19586     */
19587 
19588    if (strcasecmp(host1, host2)) {
19589       return 1;
19590    }
19591 
19592    /* Headers have easier rules to follow, so do those first */
19593    if (sip_uri_headers_cmp(headers1, headers2)) {
19594       return 1;
19595    }
19596 
19597    /* And now the parameters. Ugh */
19598    return sip_uri_params_cmp(params1, params2);
19599 }
19600 
19601 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
19602 {
19603    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
19604    struct ast_app *pickup = pbx_findapp("Pickup");
19605 
19606    if (!pickup) {
19607       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
19608       return -1;
19609    }
19610 
19611    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
19612 
19613    ast_debug(2, "About to call Pickup(%s)\n", str->str);
19614 
19615    /* There is no point in capturing the return value since pickup_exec
19616       doesn't return anything meaningful unless the passed data is an empty
19617       string (which in our case it will not be) */
19618    pbx_exec(channel, pickup, str->str);
19619 
19620    return 0;
19621 }
19622 
19623 static int sip_t38_abort(const void *data)
19624 {
19625    struct sip_pvt *p = (struct sip_pvt *) data;
19626 
19627    change_t38_state(p, T38_DISABLED);
19628    transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
19629    p->t38id = -1;
19630    dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
19631 
19632    return 0;
19633 }
19634 
19635 /*! \brief Handle incoming INVITE request
19636 \note    If the INVITE has a Replaces header, it is part of an
19637  * attended transfer. If so, we do not go through the dial
19638  * plan but tries to find the active call and masquerade
19639  * into it 
19640  */
19641 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock)
19642 {
19643    int res = 1;
19644    int gotdest;
19645    const char *p_replaces;
19646    char *replace_id = NULL;
19647    int refer_locked = 0;
19648    const char *required;
19649    unsigned int required_profile = 0;
19650    struct ast_channel *c = NULL;    /* New channel */
19651    int reinvite = 0;
19652    int rtn;
19653 
19654    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
19655    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
19656    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
19657    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
19658    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
19659    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
19660    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
19661    int dlg_min_se = -1;
19662    struct {
19663       char exten[AST_MAX_EXTENSION];
19664       char context[AST_MAX_CONTEXT];
19665    } pickup = {
19666       .exten = "",
19667    };
19668    st_ref = SESSION_TIMER_REFRESHER_AUTO;
19669 
19670    /* Find out what they support */
19671    if (!p->sipoptions) {
19672       const char *supported = get_header(req, "Supported");
19673       if (!ast_strlen_zero(supported))
19674          parse_sip_options(p, supported);
19675    }
19676 
19677    /* Find out what they require */
19678    required = get_header(req, "Require");
19679    if (!ast_strlen_zero(required)) {
19680       required_profile = parse_sip_options(NULL, required);
19681       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
19682          /* At this point we only support REPLACES and Session-Timer */
19683          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
19684          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
19685          p->invitestate = INV_COMPLETED;
19686          if (!p->lastinvite)
19687             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19688          res = -1;
19689          goto request_invite_cleanup;
19690       }
19691    }
19692 
19693    /* The option tags may be present in Supported: or Require: headers.
19694    Include the Require: option tags for further processing as well */
19695    p->sipoptions |= required_profile;
19696    p->reqsipoptions = required_profile;
19697 
19698    /* Check if this is a loop */
19699    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
19700       /* This is a call to ourself.  Send ourselves an error code and stop
19701          processing immediately, as SIP really has no good mechanism for
19702          being able to call yourself */
19703       /* If pedantic is on, we need to check the tags. If they're different, this is
19704          in fact a forked call through a SIP proxy somewhere. */
19705       int different;
19706       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
19707       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
19708       if (sip_cfg.pedanticsipchecking)
19709          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
19710       else
19711          different = strcmp(initial_rlPart2, this_rlPart2);
19712       if (!different) {
19713          transmit_response(p, "482 Loop Detected", req);
19714          p->invitestate = INV_COMPLETED;
19715          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19716          res = 0;
19717          goto request_invite_cleanup;
19718       } else {
19719          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
19720           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
19721           * that should be all we need to do.
19722           * 
19723           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
19724           * correctly instead...
19725           */
19726          char *uri = ast_strdupa(this_rlPart2);
19727          char *at = strchr(uri, '@');
19728          char *peerorhost;
19729          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
19730          transmit_response(p, "100 Trying", req);
19731          if (at) {
19732             *at = '\0';
19733          }
19734          /* Parse out "sip:" */
19735          if ((peerorhost = strchr(uri, ':'))) {
19736             *peerorhost++ = '\0';
19737          }
19738          ast_string_field_set(p, theirtag, NULL);
19739          /* Treat this as if there were a call forward instead...
19740           */
19741          ast_string_field_set(p->owner, call_forward, peerorhost);
19742          ast_queue_control(p->owner, AST_CONTROL_BUSY);
19743          res = 0;
19744          goto request_invite_cleanup;
19745       }
19746    }
19747 
19748    if (!req->ignore && p->pendinginvite) {
19749       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
19750          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
19751           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
19752           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
19753           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
19754           * credentials based on one we challenged earlier.
19755           *
19756           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
19757           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
19758           * from the previous transaction from the list of outstanding packets.
19759           */
19760          __sip_ack(p, p->pendinginvite, 1, 0);
19761       } else {
19762          /* We already have a pending invite. Sorry. You are on hold. */
19763          p->glareinvite = seqno;     /* must hold on to this seqno to process ack and retransmit correctly */
19764          if (p->rtp && find_sdp(req)) {
19765             struct sockaddr_in sin;
19766             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
19767                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
19768             } else {
19769                ast_rtp_set_alt_peer(p->rtp, &sin);
19770             }
19771             if (p->vrtp) {
19772                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
19773                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
19774                } else {
19775                   ast_rtp_set_alt_peer(p->vrtp, &sin);
19776                }
19777             }
19778          }
19779          transmit_response_reliable(p, "491 Request Pending", req);
19780          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
19781          /* Don't destroy dialog here */
19782          res = 0;
19783          goto request_invite_cleanup;
19784       }
19785    }
19786 
19787    p_replaces = get_header(req, "Replaces");
19788    if (!ast_strlen_zero(p_replaces)) {
19789       /* We have a replaces header */
19790       char *ptr;
19791       char *fromtag = NULL;
19792       char *totag = NULL;
19793       char *start, *to;
19794       int error = 0;
19795 
19796       if (p->owner) {
19797          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
19798          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19799          /* Do not destroy existing call */
19800          res = -1;
19801          goto request_invite_cleanup;
19802       }
19803 
19804       if (sipdebug)
19805          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
19806       /* Create a buffer we can manipulate */
19807       replace_id = ast_strdupa(p_replaces);
19808       ast_uri_decode(replace_id);
19809 
19810       if (!p->refer && !sip_refer_allocate(p)) {
19811          transmit_response_reliable(p, "500 Server Internal Error", req);
19812          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
19813          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19814          p->invitestate = INV_COMPLETED;
19815          res = -1;
19816          goto request_invite_cleanup;
19817       }
19818 
19819       /*  Todo: (When we find phones that support this)
19820          if the replaces header contains ";early-only"
19821          we can only replace the call in early
19822          stage, not after it's up.
19823 
19824          If it's not in early mode, 486 Busy.
19825       */
19826 
19827       /* Skip leading whitespace */
19828       replace_id = ast_skip_blanks(replace_id);
19829 
19830       start = replace_id;
19831       while ( (ptr = strsep(&start, ";")) ) {
19832          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
19833          if ( (to = strcasestr(ptr, "to-tag=") ) )
19834             totag = to + 7;   /* skip the keyword */
19835          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
19836             fromtag = to + 9; /* skip the keyword */
19837             fromtag = strsep(&fromtag, "&"); /* trim what ? */
19838          }
19839       }
19840 
19841       if (sipdebug)
19842          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
19843                  replace_id,
19844                  fromtag ? fromtag : "<no from tag>",
19845                  totag ? totag : "<no to tag>");
19846 
19847       /* Try to find call that we are replacing.
19848          If we have a Replaces header, we need to cancel that call if we succeed with this call.
19849          First we cheat a little and look for a magic call-id from phones that support
19850          dialog-info+xml so we can do technology independent pickup... */
19851       if (strncmp(replace_id, "pickup-", 7) == 0) {
19852          struct sip_pvt *subscription = NULL;
19853          replace_id += 7; /* Worst case we are looking at \0 */
19854 
19855          if ((subscription = get_sip_pvt_byid_locked(replace_id, NULL, NULL)) == NULL) {
19856             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
19857             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19858             error = 1;
19859          } else {
19860             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
19861             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
19862             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
19863             sip_pvt_unlock(subscription);
19864             if (subscription->owner) {
19865                ast_channel_unlock(subscription->owner);
19866             }
19867          }
19868       }
19869 
19870       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
19871       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
19872          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
19873          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
19874          error = 1;
19875       } else {
19876          refer_locked = 1;
19877       }
19878 
19879       /* The matched call is the call from the transferer to Asterisk .
19880          We want to bridge the bridged part of the call to the 
19881          incoming invite, thus taking over the refered call */
19882 
19883       if (p->refer->refer_call == p) {
19884          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
19885          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
19886          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
19887          error = 1;
19888       }
19889 
19890       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
19891          /* Oops, someting wrong anyway, no owner, no call */
19892          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
19893          /* Check for better return code */
19894          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
19895          error = 1;
19896       }
19897 
19898       if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
19899          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
19900          transmit_response_reliable(p, "603 Declined (Replaces)", req);
19901          error = 1;
19902       }
19903 
19904       if (error) {   /* Give up this dialog */
19905          append_history(p, "Xfer", "INVITE/Replace Failed.");
19906          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19907          sip_pvt_unlock(p);
19908          if (p->refer->refer_call) {
19909             sip_pvt_unlock(p->refer->refer_call);
19910             if (p->refer->refer_call->owner) {
19911                ast_channel_unlock(p->refer->refer_call->owner);
19912             }
19913          }
19914          refer_locked = 0;
19915          p->invitestate = INV_COMPLETED;
19916          res = -1;
19917          goto request_invite_cleanup;
19918       }
19919    }
19920 
19921    /* Check if this is an INVITE that sets up a new dialog or
19922       a re-invite in an existing dialog */
19923 
19924    if (!req->ignore) {
19925       int newcall = (p->initreq.headers ? TRUE : FALSE);
19926 
19927       if (sip_cancel_destroy(p))
19928          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
19929       /* This also counts as a pending invite */
19930       p->pendinginvite = seqno;
19931       check_via(p, req);
19932 
19933       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
19934       if (sipdebug)
19935          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19936       if (!p->owner) {  /* Not a re-invite */
19937          if (debug)
19938             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
19939          if (newcall)
19940             append_history(p, "Invite", "New call: %s", p->callid);
19941          parse_ok_contact(p, req);
19942       } else { /* Re-invite on existing call */
19943          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
19944          /* Handle SDP here if we already have an owner */
19945          if (find_sdp(req)) {
19946             if (process_sdp(p, req, SDP_T38_INITIATE)) {
19947                transmit_response_reliable(p, "488 Not acceptable here", req);
19948                if (!p->lastinvite)
19949                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19950                res = -1;
19951                goto request_invite_cleanup;
19952             }
19953             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
19954          } else {
19955             p->jointcapability = p->capability;
19956             ast_debug(1, "Hm....  No sdp for the moment\n");
19957          }
19958          if (p->do_history) /* This is a response, note what it was for */
19959             append_history(p, "ReInv", "Re-invite received");
19960       }
19961    } else if (debug)
19962       ast_verbose("Ignoring this INVITE request\n");
19963 
19964    if (!p->lastinvite && !req->ignore && !p->owner) {
19965       /* This is a new invite */
19966       /* Handle authentication if this is our first invite */
19967       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
19968       if (res == AUTH_CHALLENGE_SENT) {
19969          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
19970          res = 0;
19971          goto request_invite_cleanup;
19972       }
19973       if (res < 0) { /* Something failed in authentication */
19974          if (res == AUTH_FAKE_AUTH) {
19975             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
19976             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
19977          } else {
19978             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
19979             transmit_response_reliable(p, "403 Forbidden", req);
19980          }
19981          p->invitestate = INV_COMPLETED;
19982          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19983          ast_string_field_set(p, theirtag, NULL);
19984          res = 0;
19985          goto request_invite_cleanup;
19986       }
19987 
19988       /* If T38 is needed but not present, then make it magically appear */
19989       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && !p->udptl && (p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr))) {
19990          p->t38_maxdatagram = global_t38_maxdatagram;
19991          set_t38_capabilities(p);
19992       }
19993 
19994       /* We have a succesful authentication, process the SDP portion if there is one */
19995       if (find_sdp(req)) {
19996          if (process_sdp(p, req, SDP_T38_INITIATE)) {
19997             /* Unacceptable codecs */
19998             transmit_response_reliable(p, "488 Not acceptable here", req);
19999             p->invitestate = INV_COMPLETED;
20000             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20001             ast_debug(1, "No compatible codecs for this SIP call.\n");
20002             res = -1;
20003             goto request_invite_cleanup;
20004          }
20005          if (ast_test_flag(&p->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
20006             if (p->rtp) {
20007                ast_rtp_set_constantssrc(p->rtp);
20008             }
20009             if (p->vrtp) {
20010                ast_rtp_set_constantssrc(p->vrtp);
20011             }
20012          }
20013       } else { /* No SDP in invite, call control session */
20014          p->jointcapability = p->capability;
20015          ast_debug(2, "No SDP in Invite, third party call control\n");
20016       }
20017 
20018       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
20019       /* This seems redundant ... see !p-owner above */
20020       if (p->owner)
20021          ast_queue_frame(p->owner, &ast_null_frame);
20022 
20023 
20024       /* Initialize the context if it hasn't been already */
20025       if (ast_strlen_zero(p->context))
20026          ast_string_field_set(p, context, sip_cfg.default_context);
20027 
20028 
20029       /* Check number of concurrent calls -vs- incoming limit HERE */
20030       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
20031       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
20032          if (res < 0) {
20033             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
20034             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
20035             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20036             p->invitestate = INV_COMPLETED;
20037          }
20038          res = 0;
20039          goto request_invite_cleanup;
20040       }
20041       gotdest = get_destination(p, NULL); /* Get destination right away */
20042       get_rdnis(p, NULL);        /* Get redirect information */
20043       extract_uri(p, req);       /* Get the Contact URI */
20044       build_contact(p);       /* Build our contact header */
20045 
20046       if (p->rtp) {
20047          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
20048          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
20049       }
20050 
20051       if (!replace_id && gotdest) { /* No matching extension found */
20052          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
20053             transmit_response_reliable(p, "484 Address Incomplete", req);
20054          else {
20055             char *decoded_exten = ast_strdupa(p->exten);
20056 
20057             transmit_response_reliable(p, "404 Not Found", req);
20058             ast_uri_decode(decoded_exten);
20059             ast_log(LOG_NOTICE, "Call from '%s' to extension"
20060                " '%s' rejected because extension not found.\n",
20061                S_OR(p->username, p->peername), decoded_exten);
20062          }
20063          p->invitestate = INV_COMPLETED;
20064          update_call_counter(p, DEC_CALL_LIMIT);
20065          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20066          res = 0;
20067          goto request_invite_cleanup;
20068       } else {
20069 
20070          /* If no extension was specified, use the s one */
20071          /* Basically for calling to IP/Host name only */
20072          if (ast_strlen_zero(p->exten))
20073             ast_string_field_set(p, exten, "s");
20074          /* Initialize our tag */
20075 
20076          make_our_tag(p->tag, sizeof(p->tag));
20077          /* First invitation - create the channel */
20078          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
20079          *recount = 1;
20080 
20081          /* Save Record-Route for any later requests we make on this dialogue */
20082          build_route(p, req, 0);
20083 
20084          if (c) {
20085             /* Pre-lock the call */
20086             ast_channel_lock(c);
20087          }
20088       }
20089    } else {
20090       if (sipdebug) {
20091          if (!req->ignore)
20092             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
20093          else
20094             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
20095       }
20096       if (!req->ignore)
20097          reinvite = 1;
20098       c = p->owner;
20099    }
20100 
20101    /* Session-Timers */
20102    if (p->sipoptions & SIP_OPT_TIMER) {
20103       /* The UAC has requested session-timers for this session. Negotiate
20104       the session refresh interval and who will be the refresher */
20105       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
20106 
20107       /* Allocate Session-Timers struct w/in the dialog */
20108       if (!p->stimer)
20109          sip_st_alloc(p);
20110 
20111       /* Parse the Session-Expires header */
20112       p_uac_se_hdr = get_header(req, "Session-Expires");
20113       if (!ast_strlen_zero(p_uac_se_hdr)) {
20114          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
20115          if (rtn != 0) {
20116             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
20117             p->invitestate = INV_COMPLETED;
20118             if (!p->lastinvite) {
20119                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20120             }
20121             res = -1;
20122             goto request_invite_cleanup;
20123          }
20124       }
20125 
20126       /* Parse the Min-SE header */
20127       p_uac_min_se = get_header(req, "Min-SE");
20128       if (!ast_strlen_zero(p_uac_min_se)) {
20129          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
20130          if (rtn != 0) {
20131             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
20132             p->invitestate = INV_COMPLETED;
20133             if (!p->lastinvite) {
20134                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20135             }
20136             res = -1;
20137             goto request_invite_cleanup;
20138          }
20139       }
20140 
20141       dlg_min_se = st_get_se(p, FALSE);
20142       switch (st_get_mode(p)) {
20143       case SESSION_TIMER_MODE_ACCEPT:
20144       case SESSION_TIMER_MODE_ORIGINATE:
20145          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
20146             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
20147             p->invitestate = INV_COMPLETED;
20148             if (!p->lastinvite) {
20149                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20150             }
20151             res = -1;
20152             goto request_invite_cleanup;
20153          }
20154 
20155          p->stimer->st_active_peer_ua = TRUE;
20156          st_active = TRUE;
20157          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
20158             st_ref = st_get_refresher(p);
20159          }
20160 
20161          if (uac_max_se > 0) {
20162             int dlg_max_se = st_get_se(p, TRUE);
20163             if (dlg_max_se >= uac_min_se) {
20164                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
20165             } else {
20166                st_interval = uac_max_se;
20167             }
20168          } else {
20169             /* Set to default max value */
20170             st_interval = global_max_se;
20171          }
20172          break;
20173 
20174       case SESSION_TIMER_MODE_REFUSE:
20175          if (p->reqsipoptions & SIP_OPT_TIMER) {
20176             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
20177             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
20178             p->invitestate = INV_COMPLETED;
20179             if (!p->lastinvite) {
20180                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20181             }
20182             res = -1;
20183             goto request_invite_cleanup;
20184          }
20185          break;
20186 
20187       default:
20188          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
20189          break;
20190       }
20191    } else {
20192       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
20193       (based on session-timer-mode in sip.conf) whether to run session-timers for
20194       this session or not. */
20195       switch (st_get_mode(p)) {
20196       case SESSION_TIMER_MODE_ORIGINATE:
20197          st_active = TRUE;
20198          st_interval = st_get_se(p, TRUE);
20199          st_ref = SESSION_TIMER_REFRESHER_UAS;
20200          p->stimer->st_active_peer_ua = FALSE;
20201          break;
20202 
20203       default:
20204          break;
20205       }
20206    }
20207 
20208    if (reinvite == 0) {
20209       /* Session-Timers: Start session refresh timer based on negotiation/config */
20210       if (st_active == TRUE) {
20211          p->stimer->st_active   = TRUE;
20212          p->stimer->st_interval = st_interval;
20213          p->stimer->st_ref      = st_ref;
20214          start_session_timer(p);
20215       }
20216    } else {
20217       if (p->stimer->st_active == TRUE) {
20218          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
20219          a refresh request, no matter whether the re-invite was sent for refreshing 
20220          the session or modifying it.*/
20221          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
20222 
20223          /* The UAC may be adjusting the session-timers mid-session */
20224          if (st_interval > 0) {
20225             p->stimer->st_interval = st_interval;
20226             p->stimer->st_ref      = st_ref;
20227          }
20228 
20229          restart_session_timer(p);
20230          if (p->stimer->st_expirys > 0) {
20231             p->stimer->st_expirys--;
20232          }
20233       }
20234    }
20235 
20236    if (!req->ignore && p)
20237       p->lastinvite = seqno;
20238 
20239    if (replace_id) { /* Attended transfer or call pickup - we're the target */
20240       if (!ast_strlen_zero(pickup.exten)) {
20241          append_history(p, "Xfer", "INVITE/Replace received");
20242 
20243          /* Let the caller know we're giving it a shot */
20244          transmit_response(p, "100 Trying", req);
20245          ast_setstate(c, AST_STATE_RING);
20246 
20247          /* Do the pickup itself */
20248          ast_channel_unlock(c);
20249          *nounlock = 1;
20250          do_magic_pickup(c, pickup.exten, pickup.context);
20251 
20252          /* Now we're either masqueraded or we failed to pickup, in either case we... */
20253          sip_pvt_unlock(p);
20254          ast_hangup(c);
20255          sip_pvt_lock(p);
20256 
20257          res = 0;
20258          goto request_invite_cleanup;
20259       } else {
20260          /* Go and take over the target call */
20261          if (sipdebug)
20262             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
20263          res = handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
20264          refer_locked = 0;
20265          goto request_invite_cleanup;
20266       }
20267    }
20268 
20269 
20270    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
20271       enum ast_channel_state c_state = c->_state;
20272 
20273       if (c_state != AST_STATE_UP && reinvite &&
20274          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
20275          /* If these conditions are true, and the channel is still in the 'ringing'
20276           * state, then this likely means that we have a situation where the initial
20277           * INVITE transaction has completed *but* the channel's state has not yet been
20278           * changed to UP. The reason this could happen is if the reinvite is received
20279           * on the SIP socket prior to an application calling ast_read on this channel
20280           * to read the answer frame we earlier queued on it. In this case, the reinvite
20281           * is completely legitimate so we need to handle this the same as if the channel 
20282           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
20283           */
20284          c_state = AST_STATE_UP;
20285       }
20286 
20287       switch(c_state) {
20288       case AST_STATE_DOWN:
20289          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
20290          transmit_provisional_response(p, "100 Trying", req, 0);
20291          p->invitestate = INV_PROCEEDING;
20292          ast_setstate(c, AST_STATE_RING);
20293          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
20294             enum ast_pbx_result result;
20295 
20296             result = ast_pbx_start(c);
20297 
20298             switch(result) {
20299             case AST_PBX_FAILED:
20300                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
20301                p->invitestate = INV_COMPLETED;
20302                transmit_response_reliable(p, "503 Unavailable", req);
20303                break;
20304             case AST_PBX_CALL_LIMIT:
20305                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
20306                p->invitestate = INV_COMPLETED;
20307                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
20308                break;
20309             case AST_PBX_SUCCESS:
20310                /* nothing to do */
20311                break;
20312             }
20313 
20314             if (result) {
20315 
20316                /* Unlock locks so ast_hangup can do its magic */
20317                ast_channel_unlock(c);
20318                sip_pvt_unlock(p);
20319                ast_hangup(c);
20320                sip_pvt_lock(p);
20321                c = NULL;
20322             }
20323          } else { /* Pickup call in call group */
20324             ast_channel_unlock(c);
20325             *nounlock = 1;
20326             if (ast_pickup_call(c)) {
20327                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
20328                transmit_response_reliable(p, "503 Unavailable", req);
20329                sip_alreadygone(p);
20330                /* Unlock locks so ast_hangup can do its magic */
20331                sip_pvt_unlock(p);
20332                c->hangupcause = AST_CAUSE_CALL_REJECTED;
20333             } else {
20334                sip_pvt_unlock(p);
20335                ast_setstate(c, AST_STATE_DOWN);
20336                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20337             }
20338             p->invitestate = INV_COMPLETED;
20339             ast_hangup(c);
20340             sip_pvt_lock(p);
20341             c = NULL;
20342          }
20343          break;
20344       case AST_STATE_RING:
20345          transmit_provisional_response(p, "100 Trying", req, 0);
20346          p->invitestate = INV_PROCEEDING;
20347          break;
20348       case AST_STATE_RINGING:
20349          transmit_provisional_response(p, "180 Ringing", req, 0);
20350          p->invitestate = INV_PROCEEDING;
20351          break;
20352       case AST_STATE_UP:
20353          ast_debug(2, "%s: This call is UP.... \n", c->name);
20354 
20355          transmit_response(p, "100 Trying", req);
20356 
20357          if (p->t38.state == T38_PEER_REINVITE) {
20358             p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
20359          } else if (p->t38.state == T38_ENABLED) {
20360             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20361             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
20362          } else if (p->t38.state == T38_DISABLED) {
20363             /* If this is not a re-invite or something to ignore - it's critical */
20364             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20365             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
20366          }
20367 
20368          p->invitestate = INV_TERMINATED;
20369          break;
20370       default:
20371          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
20372          transmit_response(p, "100 Trying", req);
20373          break;
20374       }
20375    } else {
20376       if (p && (p->autokillid == -1)) {
20377          const char *msg;
20378 
20379          if (!p->jointcapability)
20380             msg = "488 Not Acceptable Here (codec error)";
20381          else {
20382             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
20383             msg = "503 Unavailable";
20384          }
20385          transmit_response_reliable(p, msg, req);
20386          p->invitestate = INV_COMPLETED;
20387          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20388       }
20389    }
20390 
20391 request_invite_cleanup:
20392 
20393    if (refer_locked && p->refer && p->refer->refer_call) {
20394       sip_pvt_unlock(p->refer->refer_call);
20395       if (p->refer->refer_call->owner) {
20396          ast_channel_unlock(p->refer->refer_call->owner);
20397       }
20398    }
20399 
20400    return res;
20401 }
20402 
20403 /*! \brief  Find all call legs and bridge transferee with target 
20404  * called from handle_request_refer */
20405 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
20406 {
20407    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
20408                /* Chan 2: Call from Asterisk to target */
20409    int res = 0;
20410    struct sip_pvt *targetcall_pvt;
20411 
20412    /* Check if the call ID of the replaces header does exist locally */
20413    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
20414       transferer->refer->replaces_callid_fromtag))) {
20415       if (transferer->refer->localtransfer) {
20416          /* We did not find the refered call. Sorry, can't accept then */
20417          transmit_response(transferer, "202 Accepted", req);
20418          /* Let's fake a response from someone else in order
20419             to follow the standard */
20420          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
20421          append_history(transferer, "Xfer", "Refer failed");
20422          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
20423          transferer->refer->status = REFER_FAILED;
20424          return -1;
20425       }
20426       /* Fall through for remote transfers that we did not find locally */
20427       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
20428       return 0;
20429    }
20430 
20431    /* Ok, we can accept this transfer */
20432    transmit_response(transferer, "202 Accepted", req);
20433    append_history(transferer, "Xfer", "Refer accepted");
20434    if (!targetcall_pvt->owner) { /* No active channel */
20435       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
20436       /* Cancel transfer */
20437       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
20438       append_history(transferer, "Xfer", "Refer failed");
20439       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
20440       transferer->refer->status = REFER_FAILED;
20441       sip_pvt_unlock(targetcall_pvt);
20442       if (targetcall_pvt)
20443          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
20444       return -1;
20445    }
20446 
20447    /* We have a channel, find the bridge */
20448    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
20449    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
20450 
20451    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
20452       /* Wrong state of new channel */
20453       if (target.chan2) 
20454          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
20455       else if (target.chan1->_state != AST_STATE_RING)
20456          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
20457       else
20458          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
20459    }
20460 
20461    /* Transfer */
20462    if (sipdebug) {
20463       if (current->chan2)  /* We have two bridges */
20464          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
20465       else        /* One bridge, propably transfer of IVR/voicemail etc */
20466          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
20467    }
20468 
20469    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20470 
20471    /* Perform the transfer */
20472    manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Attended\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\n",
20473       transferer->owner->name,
20474       transferer->owner->uniqueid,
20475       transferer->callid,
20476       target.chan1->name,
20477       target.chan1->uniqueid);
20478    res = attempt_transfer(current, &target);
20479    sip_pvt_unlock(targetcall_pvt);
20480    if (res) {
20481       /* Failed transfer */
20482       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
20483       append_history(transferer, "Xfer", "Refer failed");
20484       if (targetcall_pvt->owner)
20485          ast_channel_unlock(targetcall_pvt->owner);
20486       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
20487    } else {
20488       /* Transfer succeeded! */
20489       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
20490 
20491       /* Tell transferer that we're done. */
20492       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
20493       append_history(transferer, "Xfer", "Refer succeeded");
20494       transferer->refer->status = REFER_200OK;
20495       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
20496          ast_waitstream(target.chan2, "");
20497       }
20498       if (targetcall_pvt->owner) {
20499          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
20500          ast_channel_unlock(targetcall_pvt->owner);
20501       }
20502    }
20503    if (targetcall_pvt)
20504       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
20505    return 1;
20506 }
20507 
20508 
20509 /*! \brief Handle incoming REFER request */
20510 /*! \page SIP_REFER SIP transfer Support (REFER)
20511 
20512    REFER is used for call transfer in SIP. We get a REFER
20513    to place a new call with an INVITE somwhere and then
20514    keep the transferor up-to-date of the transfer. If the
20515    transfer fails, get back on line with the orginal call. 
20516 
20517    - REFER can be sent outside or inside of a dialog.
20518      Asterisk only accepts REFER inside of a dialog.
20519 
20520    - If we get a replaces header, it is an attended transfer
20521 
20522    \par Blind transfers
20523    The transferor provides the transferee
20524    with the transfer targets contact. The signalling between
20525    transferer or transferee should not be cancelled, so the
20526    call is recoverable if the transfer target can not be reached 
20527    by the transferee.
20528 
20529    In this case, Asterisk receives a TRANSFER from
20530    the transferor, thus is the transferee. We should
20531    try to set up a call to the contact provided
20532    and if that fails, re-connect the current session.
20533    If the new call is set up, we issue a hangup.
20534    In this scenario, we are following section 5.2
20535    in the SIP CC Transfer draft. (Transfer without
20536    a GRUU)
20537 
20538    \par Transfer with consultation hold
20539    In this case, the transferor
20540    talks to the transfer target before the transfer takes place.
20541    This is implemented with SIP hold and transfer.
20542    Note: The invite From: string could indicate a transfer.
20543    (Section 6. Transfer with consultation hold)
20544    The transferor places the transferee on hold, starts a call
20545    with the transfer target to alert them to the impending
20546    transfer, terminates the connection with the target, then
20547    proceeds with the transfer (as in Blind transfer above)
20548 
20549    \par Attended transfer
20550    The transferor places the transferee
20551    on hold, calls the transfer target to alert them,
20552    places the target on hold, then proceeds with the transfer
20553    using a Replaces header field in the Refer-to header. This
20554    will force the transfee to send an Invite to the target,
20555    with a replaces header that instructs the target to
20556    hangup the call between the transferor and the target.
20557    In this case, the Refer/to: uses the AOR address. (The same
20558    URI that the transferee used to establish the session with
20559    the transfer target (To: ). The Require: replaces header should
20560    be in the INVITE to avoid the wrong UA in a forked SIP proxy
20561    scenario to answer and have no call to replace with.
20562 
20563    The referred-by header is *NOT* required, but if we get it,
20564    can be copied into the INVITE to the transfer target to 
20565    inform the target about the transferor
20566 
20567    "Any REFER request has to be appropriately authenticated.".
20568    
20569    We can't destroy dialogs, since we want the call to continue.
20570    
20571    */
20572 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
20573 {
20574    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
20575                /* Chan2: Call between asterisk and transferee */
20576 
20577    int res = 0;
20578    current.req.data = NULL;
20579 
20580    if (req->debug)
20581       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n", p->callid, ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
20582 
20583    if (!p->owner) {
20584       /* This is a REFER outside of an existing SIP dialog */
20585       /* We can't handle that, so decline it */
20586       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
20587       transmit_response(p, "603 Declined (No dialog)", req);
20588       if (!req->ignore) {
20589          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
20590          sip_alreadygone(p);
20591          pvt_set_needdestroy(p, "outside of dialog");
20592       }
20593       return 0;
20594    }
20595 
20596 
20597    /* Check if transfer is allowed from this device */
20598    if (p->allowtransfer == TRANSFER_CLOSED ) {
20599       /* Transfer not allowed, decline */
20600       transmit_response(p, "603 Declined (policy)", req);
20601       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
20602       /* Do not destroy SIP session */
20603       return 0;
20604    }
20605 
20606    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
20607       /* Already have a pending REFER */
20608       transmit_response(p, "491 Request pending", req);
20609       append_history(p, "Xfer", "Refer failed. Request pending.");
20610       return 0;
20611    }
20612 
20613    /* Allocate memory for call transfer data */
20614    if (!p->refer && !sip_refer_allocate(p)) {
20615       transmit_response(p, "500 Internal Server Error", req);
20616       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
20617       return -3;
20618    }
20619 
20620    res = get_refer_info(p, req); /* Extract headers */
20621 
20622    p->refer->status = REFER_SENT;
20623 
20624    if (res != 0) {
20625       switch (res) {
20626       case -2: /* Syntax error */
20627          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
20628          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
20629          if (req->debug)
20630             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
20631          break;
20632       case -3:
20633          transmit_response(p, "603 Declined (Non sip: uri)", req);
20634          append_history(p, "Xfer", "Refer failed. Non SIP uri");
20635          if (req->debug)
20636             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
20637          break;
20638       default:
20639          /* Refer-to extension not found, fake a failed transfer */
20640          transmit_response(p, "202 Accepted", req);
20641          append_history(p, "Xfer", "Refer failed. Bad extension.");
20642          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
20643          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20644          if (req->debug)
20645             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
20646          break;
20647       } 
20648       return 0;
20649    }
20650    if (ast_strlen_zero(p->context))
20651       ast_string_field_set(p, context, sip_cfg.default_context);
20652 
20653    /* If we do not support SIP domains, all transfers are local */
20654    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20655       p->refer->localtransfer = 1;
20656       if (sipdebug)
20657          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
20658    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
20659       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
20660       p->refer->localtransfer = 1;
20661    } else if (sipdebug)
20662          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
20663 
20664    /* Is this a repeat of a current request? Ignore it */
20665    /* Don't know what else to do right now. */
20666    if (req->ignore) 
20667       return res;
20668 
20669    /* If this is a blind transfer, we have the following
20670    channels to work with:
20671    - chan1, chan2: The current call between transferer and transferee (2 channels)
20672    - target_channel: A new call from the transferee to the target (1 channel)
20673    We need to stay tuned to what happens in order to be able
20674    to bring back the call to the transferer */
20675 
20676    /* If this is a attended transfer, we should have all call legs within reach:
20677    - chan1, chan2: The call between the transferer and transferee (2 channels)
20678    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
20679    We want to bridge chan2 with targetcall_pvt!
20680    
20681    The replaces call id in the refer message points
20682    to the call leg between Asterisk and the transferer.
20683    So we need to connect the target and the transferee channel
20684    and hangup the two other channels silently 
20685    
20686    If the target is non-local, the call ID could be on a remote
20687    machine and we need to send an INVITE with replaces to the
20688    target. We basically handle this as a blind transfer
20689    and let the sip_call function catch that we need replaces
20690    header in the INVITE.
20691    */
20692 
20693 
20694    /* Get the transferer's channel */
20695    current.chan1 = p->owner;
20696 
20697    /* Find the other part of the bridge (2) - transferee */
20698    current.chan2 = ast_bridged_channel(current.chan1);
20699    
20700    if (sipdebug)
20701       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n", p->refer->attendedtransfer ? "attended" : "blind", current.chan1->name, current.chan2 ? current.chan2->name : "<none>");
20702 
20703    if (!current.chan2 && !p->refer->attendedtransfer) {
20704       /* No bridged channel, propably IVR or echo or similar... */
20705       /* Guess we should masquerade or something here */
20706       /* Until we figure it out, refuse transfer of such calls */
20707       if (sipdebug)
20708          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
20709       p->refer->status = REFER_FAILED;
20710       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
20711       transmit_response(p, "603 Declined", req);
20712       return -1;
20713    }
20714 
20715    if (current.chan2) {
20716       if (sipdebug)
20717          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
20718 
20719       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
20720    }
20721 
20722    ast_set_flag(&p->flags[0], SIP_GOTREFER);
20723 
20724    /* Attended transfer: Find all call legs and bridge transferee with target*/
20725    if (p->refer->attendedtransfer) {
20726       if ((res = local_attended_transfer(p, &current, req, seqno)))
20727          return res; /* We're done with the transfer */
20728       /* Fall through for remote transfers that we did not find locally */
20729       if (sipdebug)
20730          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
20731       /* Fallthrough if we can't find the call leg internally */
20732    }
20733 
20734 
20735    /* Parking a call */
20736    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
20737       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
20738       *nounlock = 1;
20739       ast_channel_unlock(current.chan1);
20740       copy_request(&current.req, req);
20741       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
20742       p->refer->status = REFER_200OK;
20743       append_history(p, "Xfer", "REFER to call parking.");
20744       manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransfer2Parking: Yes\r\n",
20745          current.chan1->name,
20746          current.chan1->uniqueid,
20747          p->callid,
20748          current.chan2->name,
20749          current.chan2->uniqueid,
20750          p->refer->refer_to);
20751       if (sipdebug)
20752          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
20753       sip_park(current.chan2, current.chan1, req, seqno);
20754       return res;
20755    } 
20756 
20757    /* Blind transfers and remote attended xfers */
20758    transmit_response(p, "202 Accepted", req);
20759 
20760    if (current.chan1 && current.chan2) {
20761       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
20762       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
20763    }
20764    if (current.chan2) {
20765       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
20766       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
20767       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
20768       /* One for the new channel */
20769       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
20770       /* Attended transfer to remote host, prepare headers for the INVITE */
20771       if (p->refer->referred_by) 
20772          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
20773    }
20774    /* Generate a Replaces string to be used in the INVITE during attended transfer */
20775    if (!ast_strlen_zero(p->refer->replaces_callid)) {
20776       char tempheader[SIPBUFSIZE];
20777       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
20778             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
20779             p->refer->replaces_callid_totag, 
20780             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
20781             p->refer->replaces_callid_fromtag);
20782       if (current.chan2)
20783          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
20784    }
20785    /* Must release lock now, because it will not longer
20786       be accessible after the transfer! */
20787    *nounlock = 1;
20788    ast_channel_unlock(current.chan1);
20789 
20790    /* Connect the call */
20791 
20792    /* FAKE ringing if not attended transfer */
20793    if (!p->refer->attendedtransfer)
20794       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
20795 
20796    /* For blind transfer, this will lead to a new call */
20797    /* For attended transfer to remote host, this will lead to
20798       a new SIP call with a replaces header, if the dial plan allows it 
20799    */
20800    if (!current.chan2) {
20801       /* We have no bridge, so we're talking with Asterisk somehow */
20802       /* We need to masquerade this call */
20803       /* What to do to fix this situation:
20804          * Set up the new call in a new channel 
20805          * Let the new channel masq into this channel
20806          Please add that code here :-)
20807       */
20808       p->refer->status = REFER_FAILED;
20809       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
20810       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20811       append_history(p, "Xfer", "Refer failed (only bridged calls).");
20812       return -1;
20813    }
20814    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
20815 
20816 
20817    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
20818       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
20819    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
20820 
20821    if (!res) {
20822       manager_event(EVENT_FLAG_CALL, "Transfer", "TransferMethod: SIP\r\nTransferType: Blind\r\nChannel: %s\r\nUniqueid: %s\r\nSIP-Callid: %s\r\nTargetChannel: %s\r\nTargetUniqueid: %s\r\nTransferExten: %s\r\nTransferContext: %s\r\n",
20823          current.chan1->name,
20824          current.chan1->uniqueid,
20825          p->callid,
20826          current.chan2->name,
20827          current.chan2->uniqueid,
20828          p->refer->refer_to, p->refer->refer_to_context);
20829       /* Success  - we have a new channel */
20830       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20831       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
20832       if (p->refer->localtransfer)
20833          p->refer->status = REFER_200OK;
20834       if (p->owner)
20835          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
20836       append_history(p, "Xfer", "Refer succeeded.");
20837       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20838       /* Do not hangup call, the other side do that when we say 200 OK */
20839       /* We could possibly implement a timer here, auto congestion */
20840       res = 0;
20841    } else {
20842       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
20843       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
20844       append_history(p, "Xfer", "Refer failed.");
20845       /* Failure of some kind */
20846       p->refer->status = REFER_FAILED;
20847       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
20848       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
20849       res = -1;
20850    }
20851    return res;
20852 }
20853 
20854 /*! \brief Handle incoming CANCEL request */
20855 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
20856 {
20857       
20858    check_via(p, req);
20859    sip_alreadygone(p);
20860 
20861    /* At this point, we could have cancelled the invite at the same time
20862       as the other side sends a CANCEL. Our final reply with error code
20863       might not have been received by the other side before the CANCEL
20864       was sent, so let's just give up retransmissions and waiting for
20865       ACK on our error code. The call is hanging up any way. */
20866    if (p->invitestate == INV_TERMINATED)
20867       __sip_pretend_ack(p);
20868    else
20869       p->invitestate = INV_CANCELLED;
20870    
20871    if (p->owner && p->owner->_state == AST_STATE_UP) {
20872       /* This call is up, cancel is ignored, we need a bye */
20873       transmit_response(p, "200 OK", req);
20874       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
20875       return 0;
20876    }
20877 
20878    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
20879       update_call_counter(p, DEC_CALL_LIMIT);
20880 
20881    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
20882    if (p->owner)
20883       ast_queue_hangup(p->owner);
20884    else
20885       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20886    if (p->initreq.len > 0) {
20887       struct sip_pkt *pkt, *prev_pkt;
20888       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
20889        * a reliable 487, then we don't want to schedule another one on top of the previous
20890        * one.
20891        *
20892        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
20893        * response in this situation. What if we've sent all of our reliable responses 
20894        * already and now all of a sudden, we get this second CANCEL?
20895        *
20896        * The only way to do this correctly is to cancel our previously-scheduled reliably-
20897        * transmitted response and send a new one in its place.
20898        */
20899       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
20900          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
20901             AST_SCHED_DEL(sched, pkt->retransid);
20902             UNLINK(pkt, p->packets, prev_pkt);
20903             ast_free(pkt);
20904             break;
20905          }
20906       }
20907       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
20908       transmit_response(p, "200 OK", req);
20909       return 1;
20910    } else {
20911       transmit_response(p, "481 Call Leg Does Not Exist", req);
20912       return 0;
20913    }
20914 }
20915 
20916 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
20917 {
20918    struct sip_pvt *p = chan->tech_pvt;
20919    char *all = "", *parse = ast_strdupa(preparse);
20920    int res = 0;
20921    AST_DECLARE_APP_ARGS(args,
20922       AST_APP_ARG(param);
20923       AST_APP_ARG(type);
20924       AST_APP_ARG(field);
20925    );
20926    AST_STANDARD_APP_ARGS(args, parse);
20927 
20928    /* Sanity check */
20929    if (!IS_SIP_TECH(chan->tech)) {
20930       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
20931       return 0;
20932    }
20933 
20934    memset(buf, 0, buflen);
20935 
20936    if (p == NULL) {
20937       return -1;
20938    }
20939 
20940    if (!strcasecmp(args.param, "peerip")) {
20941       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
20942    } else if (!strcasecmp(args.param, "recvip")) {
20943       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
20944    } else if (!strcasecmp(args.param, "from")) {
20945       ast_copy_string(buf, p->from, buflen);
20946    } else if (!strcasecmp(args.param, "uri")) {
20947       ast_copy_string(buf, p->uri, buflen);
20948    } else if (!strcasecmp(args.param, "useragent")) {
20949       ast_copy_string(buf, p->useragent, buflen);
20950    } else if (!strcasecmp(args.param, "peername")) {
20951       ast_copy_string(buf, p->peername, buflen);
20952    } else if (!strcasecmp(args.param, "t38passthrough")) {
20953       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
20954    } else if (!strcasecmp(args.param, "rtpdest")) {
20955       struct sockaddr_in sin;
20956 
20957       if (ast_strlen_zero(args.type))
20958          args.type = "audio";
20959 
20960       if (!strcasecmp(args.type, "audio"))
20961          ast_rtp_get_peer(p->rtp, &sin);
20962       else if (!strcasecmp(args.type, "video"))
20963          ast_rtp_get_peer(p->vrtp, &sin);
20964       else if (!strcasecmp(args.type, "text"))
20965          ast_rtp_get_peer(p->trtp, &sin);
20966       else
20967          return -1;
20968 
20969       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
20970    } else if (!strcasecmp(args.param, "rtpqos")) {
20971       struct ast_rtp_quality qos;
20972       struct ast_rtp *rtp = p->rtp;
20973       
20974       memset(&qos, 0, sizeof(qos));
20975 
20976       if (ast_strlen_zero(args.type))
20977          args.type = "audio";
20978       if (ast_strlen_zero(args.field))
20979          args.field = "all";
20980       
20981       if (!strcasecmp(args.type, "AUDIO")) {
20982          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
20983       } else if (!strcasecmp(args.type, "VIDEO")) {
20984          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
20985       } else if (!strcasecmp(args.type, "TEXT")) {
20986          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
20987       } else {
20988          return -1;
20989       }
20990       
20991       if (!strcasecmp(args.field, "local_ssrc"))
20992          snprintf(buf, buflen, "%u", qos.local_ssrc);
20993       else if (!strcasecmp(args.field, "local_lostpackets"))
20994          snprintf(buf, buflen, "%u", qos.local_lostpackets);
20995       else if (!strcasecmp(args.field, "local_jitter"))
20996          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
20997       else if (!strcasecmp(args.field, "local_count"))
20998          snprintf(buf, buflen, "%u", qos.local_count);
20999       else if (!strcasecmp(args.field, "remote_ssrc"))
21000          snprintf(buf, buflen, "%u", qos.remote_ssrc);
21001       else if (!strcasecmp(args.field, "remote_lostpackets"))
21002          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
21003       else if (!strcasecmp(args.field, "remote_jitter"))
21004          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
21005       else if (!strcasecmp(args.field, "remote_count"))
21006          snprintf(buf, buflen, "%u", qos.remote_count);
21007       else if (!strcasecmp(args.field, "rtt"))
21008          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
21009       else if (!strcasecmp(args.field, "all"))
21010          ast_copy_string(buf, all, buflen);
21011       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
21012           ;
21013       else {
21014          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
21015          return -1;
21016       }
21017    } else {
21018       res = -1;
21019    }
21020    return res;
21021 }
21022 
21023 /*! \brief Handle incoming BYE request */
21024 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
21025 {
21026    struct ast_channel *c=NULL;
21027    int res;
21028    struct ast_channel *bridged_to;
21029    
21030    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
21031    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
21032       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
21033    }
21034 
21035    __sip_pretend_ack(p);
21036 
21037    p->invitestate = INV_TERMINATED;
21038 
21039    copy_request(&p->initreq, req);
21040    if (sipdebug)
21041       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21042    check_via(p, req);
21043    sip_alreadygone(p);
21044 
21045    /* Get RTCP quality before end of call */
21046    if (p->do_history || p->owner) {
21047       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21048       char *videoqos, *textqos;
21049 
21050       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
21051        * to lock the bridge. This may get hairy...
21052        */
21053       while (bridge && ast_channel_trylock(bridge)) {
21054          ast_channel_unlock(p->owner);
21055          do {
21056             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
21057             sip_pvt_unlock(p);
21058             usleep(1);
21059             sip_pvt_lock(p);
21060          } while (p->owner && ast_channel_trylock(p->owner));
21061          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
21062       }
21063 
21064       if (p->rtp) {  
21065          if (p->do_history) {
21066             char *audioqos,
21067                  *audioqos_jitter,
21068                  *audioqos_loss,
21069                  *audioqos_rtt;
21070 
21071             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
21072             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
21073             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
21074             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
21075 
21076             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
21077             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
21078             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
21079             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
21080          }
21081          
21082          if (p->owner) {
21083             ast_rtp_set_vars(p->owner, p->rtp);
21084          }
21085       }
21086 
21087       if (bridge) {
21088          struct sip_pvt *q = bridge->tech_pvt;
21089 
21090          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
21091             ast_rtp_set_vars(bridge, q->rtp);
21092          ast_channel_unlock(bridge);
21093       }
21094 
21095       if (p->vrtp) {
21096          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
21097          if (p->do_history)
21098             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
21099          if (p->owner)
21100             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
21101       }
21102 
21103       if (p->trtp) {
21104          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
21105          if (p->do_history)
21106             append_history(p, "RTCPtext", "Quality:%s", textqos);
21107          if (p->owner)
21108             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
21109       }
21110    }
21111 
21112    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21113    stop_session_timer(p); /* Stop Session-Timer */
21114 
21115    if (!ast_strlen_zero(get_header(req, "Also"))) {
21116       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
21117          ast_inet_ntoa(p->recv.sin_addr));
21118       if (ast_strlen_zero(p->context))
21119          ast_string_field_set(p, context, sip_cfg.default_context);
21120       res = get_also_info(p, req);
21121       if (!res) {
21122          c = p->owner;
21123          if (c) {
21124             bridged_to = ast_bridged_channel(c);
21125             if (bridged_to) {
21126                /* Don't actually hangup here... */
21127                ast_queue_control(c, AST_CONTROL_UNHOLD);
21128                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
21129             } else
21130                ast_queue_hangup(p->owner);
21131          }
21132       } else {
21133          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
21134          if (p->owner)
21135             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
21136       }
21137    } else if (p->owner) {
21138       ast_queue_hangup(p->owner);
21139       ast_debug(3, "Received bye, issuing owner hangup\n");
21140    } else {
21141       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21142       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
21143    }
21144    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21145    transmit_response(p, "200 OK", req);
21146 
21147    return 1;
21148 }
21149 
21150 /*! \brief Handle incoming MESSAGE request */
21151 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
21152 {
21153    if (!req->ignore) {
21154       if (req->debug)
21155          ast_verbose("Receiving message!\n");
21156       receive_message(p, req);
21157    } else
21158       transmit_response(p, "202 Accepted", req);
21159    return 1;
21160 }
21161 
21162 static void add_peer_mwi_subs(struct sip_peer *peer)
21163 {
21164    struct sip_mailbox *mailbox;
21165 
21166    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21167       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
21168          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21169          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21170          AST_EVENT_IE_END);
21171    }
21172 }
21173 
21174 /*! \brief  Handle incoming SUBSCRIBE request */
21175 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
21176 {
21177    int gotdest = 0;
21178    int res = 0;
21179    int firststate = AST_EXTENSION_REMOVED;
21180    struct sip_peer *authpeer = NULL;
21181    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
21182    const char *acceptheader = get_header(req, "Accept");
21183    int resubscribe = (p->subscribed != NONE);
21184    char *temp, *event;
21185    struct ao2_iterator i;
21186 
21187    if (p->initreq.headers) {  
21188       /* We already have a dialog */
21189       if (p->initreq.method != SIP_SUBSCRIBE) {
21190          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
21191          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
21192          transmit_response(p, "403 Forbidden (within dialog)", req);
21193          /* Do not destroy session, since we will break the call if we do */
21194          ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
21195          return 0;
21196       } else if (req->debug) {
21197          if (resubscribe)
21198             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
21199          else
21200             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
21201       }
21202    }
21203 
21204    /* Check if we have a global disallow setting on subscriptions. 
21205       if so, we don't have to check peer settings after auth, which saves a lot of processing
21206    */
21207    if (!sip_cfg.allowsubscribe) {
21208       transmit_response(p, "403 Forbidden (policy)", req);
21209       pvt_set_needdestroy(p, "forbidden");
21210       return 0;
21211    }
21212 
21213    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
21214       const char *to = get_header(req, "To");
21215       char totag[128];
21216 
21217       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
21218       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
21219          if (req->debug)
21220             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
21221          transmit_response(p, "481 Subscription does not exist", req);
21222          pvt_set_needdestroy(p, "subscription does not exist");
21223          return 0;
21224       }
21225 
21226       /* Use this as the basis */
21227       if (req->debug)
21228          ast_verbose("Creating new subscription\n");
21229 
21230       copy_request(&p->initreq, req);
21231       if (sipdebug)
21232          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21233       check_via(p, req);
21234       build_route(p, req, 0);
21235    } else if (req->debug && req->ignore)
21236       ast_verbose("Ignoring this SUBSCRIBE request\n");
21237 
21238    /* Find parameters to Event: header value and remove them for now */
21239    if (ast_strlen_zero(eventheader)) {
21240       transmit_response(p, "489 Bad Event", req);
21241       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
21242       pvt_set_needdestroy(p, "unknown event package in subscribe");
21243       return 0;
21244    }
21245 
21246    if ( (strchr(eventheader, ';'))) {
21247       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
21248       temp = strchr(event, ';');       
21249       *temp = '\0';           /* Remove any options for now */
21250                      /* We might need to use them later :-) */
21251    } else
21252       event = (char *) eventheader;    /* XXX is this legal ? */
21253 
21254    /* Handle authentication */
21255    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
21256    /* if an authentication response was sent, we are done here */
21257    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
21258       return 0;
21259    if (res < 0) {
21260       if (res == AUTH_FAKE_AUTH) {
21261          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
21262          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
21263       } else {
21264          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
21265          transmit_response_reliable(p, "403 Forbidden", req);
21266       }
21267       pvt_set_needdestroy(p, "authentication failed");
21268       return 0;
21269    }
21270 
21271    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
21272     * so we must release it when done.
21273     * XXX must remove all the checks for authpeer == NULL.
21274     */
21275 
21276    /* Check if this device  is allowed to subscribe at all */
21277    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
21278       transmit_response(p, "403 Forbidden (policy)", req);
21279       pvt_set_needdestroy(p, "subscription not allowed");
21280       if (authpeer)
21281          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
21282       return 0;
21283    }
21284 
21285    if (strcmp(event, "message-summary")) {
21286       /* Get destination right away */
21287       gotdest = get_destination(p, NULL);
21288    }
21289 
21290    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
21291    parse_ok_contact(p, req);
21292 
21293    build_contact(p);
21294    if (gotdest) {
21295       transmit_response(p, "404 Not Found", req);
21296       pvt_set_needdestroy(p, "subscription target not found");
21297       if (authpeer)
21298          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21299       return 0;
21300    }
21301 
21302    /* Initialize tag for new subscriptions */   
21303    if (ast_strlen_zero(p->tag))
21304       make_our_tag(p->tag, sizeof(p->tag));
21305 
21306    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
21307       unsigned int pidf_xml;
21308 
21309       if (authpeer)  /* We do not need the authpeer any more */
21310          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
21311 
21312       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
21313 
21314       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
21315 
21316       /* Older versions of Polycom firmware will claim pidf+xml, but really
21317        * they only support xpidf+xml. */
21318       if (pidf_xml && strstr(p->useragent, "Polycom")) {
21319          p->subscribed = XPIDF_XML;
21320       } else if (pidf_xml) {
21321          p->subscribed = PIDF_XML;         /* RFC 3863 format */
21322       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
21323          p->subscribed = DIALOG_INFO_XML;
21324          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
21325       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
21326          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
21327       } else if (strstr(acceptheader, "application/xpidf+xml")) {
21328          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
21329       } else if (ast_strlen_zero(acceptheader)) {
21330          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
21331             transmit_response(p, "489 Bad Event", req);
21332   
21333             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21334                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21335             pvt_set_needdestroy(p, "no Accept header");
21336             return 0;
21337          }
21338          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
21339             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
21340       } else {
21341          /* Can't find a format for events that we know about */
21342          char mybuf[200];
21343          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
21344          transmit_response(p, mybuf, req);
21345  
21346          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
21347             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
21348          pvt_set_needdestroy(p, "unrecognized format");
21349          return 0;
21350       }
21351    } else if (!strcmp(event, "message-summary")) { 
21352       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
21353          /* Format requested that we do not support */
21354          transmit_response(p, "406 Not Acceptable", req);
21355          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
21356          pvt_set_needdestroy(p, "unknown format");
21357          if (authpeer)
21358             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
21359          return 0;
21360       }
21361       /* Looks like they actually want a mailbox status 
21362         This version of Asterisk supports mailbox subscriptions
21363         The subscribed URI needs to exist in the dial plan
21364         In most devices, this is configurable to the voicemailmain extension you use
21365       */
21366       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
21367          transmit_response(p, "404 Not found (no mailbox)", req);
21368          pvt_set_needdestroy(p, "received 404 response");
21369          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
21370          if (authpeer)
21371             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
21372          return 0;
21373       }
21374 
21375       p->subscribed = MWI_NOTIFICATION;
21376       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
21377          add_peer_mwi_subs(authpeer);
21378       }
21379       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
21380          /* We only allow one subscription per peer */
21381          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
21382          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
21383          /* sip_destroy(authpeer->mwipvt); */
21384       }
21385       if (authpeer->mwipvt)
21386          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
21387       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
21388       if (p->relatedpeer)
21389          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
21390       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
21391       /* Do not release authpeer here */
21392    } else { /* At this point, Asterisk does not understand the specified event */
21393       transmit_response(p, "489 Bad Event", req);
21394       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
21395       pvt_set_needdestroy(p, "unknown event package");
21396       if (authpeer)
21397          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
21398       return 0;
21399    }
21400 
21401    /* Add subscription for extension state from the PBX core */
21402    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
21403       if (p->stateid > -1) {
21404          ast_extension_state_del(p->stateid, cb_extensionstate);
21405          /* we need to dec the refcount, now that the extensionstate is removed */
21406          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
21407       }
21408       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
21409    }
21410 
21411    if (!req->ignore && p)
21412       p->lastinvite = seqno;
21413    if (p && !p->needdestroy) {
21414       p->expiry = atoi(get_header(req, "Expires"));
21415 
21416       /* check if the requested expiry-time is within the approved limits from sip.conf */
21417       if (p->expiry > max_expiry)
21418          p->expiry = max_expiry;
21419       if (p->expiry < min_expiry && p->expiry > 0)
21420          p->expiry = min_expiry;
21421 
21422       if (sipdebug) {
21423          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
21424             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
21425          else
21426             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
21427       }
21428       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
21429          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21430       if (p->expiry > 0)
21431          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
21432 
21433       if (p->subscribed == MWI_NOTIFICATION) {
21434          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21435          transmit_response(p, "200 OK", req);
21436          if (p->relatedpeer) {   /* Send first notification */
21437             ao2_lock(p->relatedpeer); /* was WRLOCK */
21438             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
21439             ao2_unlock(p->relatedpeer);
21440          }
21441       } else {
21442          struct sip_pvt *p_old;
21443 
21444          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
21445 
21446             ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_inet_ntoa(p->sa.sin_addr));
21447             transmit_response(p, "404 Not found", req);
21448             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
21449             return 0;
21450          }
21451          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21452          transmit_response(p, "200 OK", req);
21453          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
21454          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
21455          /* hide the 'complete' exten/context in the refer_to field for later display */
21456          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
21457 
21458          /* remove any old subscription from this peer for the same exten/context,
21459          as the peer has obviously forgotten about it and it's wasteful to wait
21460          for it to expire and send NOTIFY messages to the peer only to have them
21461          ignored (or generate errors)
21462          */
21463          i = ao2_iterator_init(dialogs, 0);
21464          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21465             if (p_old == p) {
21466                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21467                continue;
21468             }
21469             if (p_old->initreq.method != SIP_SUBSCRIBE) {
21470                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21471                continue;
21472             }
21473             if (p_old->subscribed == NONE) {
21474                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
21475                continue;
21476             }
21477             sip_pvt_lock(p_old);
21478             if (!strcmp(p_old->username, p->username)) {
21479                if (!strcmp(p_old->exten, p->exten) &&
21480                    !strcmp(p_old->context, p->context)) {
21481                   pvt_set_needdestroy(p_old, "replacing subscription");
21482                   sip_pvt_unlock(p_old);
21483                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
21484                   break;
21485                }
21486             }
21487             sip_pvt_unlock(p_old);
21488             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
21489          }
21490          ao2_iterator_destroy(&i);
21491       }
21492       if (!p->expiry) {
21493          pvt_set_needdestroy(p, "forcing expiration");
21494       }
21495    }
21496    return 1;
21497 }
21498 
21499 /*! \brief Handle incoming REGISTER request */
21500 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
21501 {
21502    enum check_auth_result res;
21503 
21504    /* Use this as the basis */
21505    copy_request(&p->initreq, req);
21506    if (sipdebug)
21507       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
21508    check_via(p, req);
21509    if ((res = register_verify(p, sin, req, e)) < 0) {
21510       const char *reason;
21511 
21512       switch (res) {
21513       case AUTH_SECRET_FAILED:
21514          reason = "Wrong password";
21515          break;
21516       case AUTH_USERNAME_MISMATCH:
21517          reason = "Username/auth name mismatch";
21518          break;
21519       case AUTH_NOT_FOUND:
21520          reason = "No matching peer found";
21521          break;
21522       case AUTH_UNKNOWN_DOMAIN:
21523          reason = "Not a local domain";
21524          break;
21525       case AUTH_PEER_NOT_DYNAMIC:
21526          reason = "Peer is not supposed to register";
21527          break;
21528       case AUTH_ACL_FAILED:
21529          reason = "Device does not match ACL";
21530          break;
21531       case AUTH_BAD_TRANSPORT:
21532          reason = "Device not configured to use this transport type";
21533          break;
21534       default:
21535          reason = "Unknown failure";
21536          break;
21537       }
21538       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
21539          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
21540          reason);
21541       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
21542    } else
21543       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
21544 
21545    if (res < 1) {
21546       /* Destroy the session, but keep us around for just a bit in case they don't
21547          get our 200 OK */
21548       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21549    }
21550    return res;
21551 }
21552 
21553 /*! \brief Handle incoming SIP requests (methods) 
21554 \note This is where all incoming requests go first   */
21555 /* called with p and p->owner locked */
21556 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
21557 {
21558    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
21559       relatively static */
21560    const char *cmd;
21561    const char *cseq;
21562    const char *useragent;
21563    int seqno;
21564    int len;
21565    int respid;
21566    int res = 0;
21567    int debug = sip_debug_test_pvt(p);
21568    char *e;
21569    int error = 0;
21570    int oldmethod = p->method;
21571    int acked = 0;
21572 
21573    /* Get Method and Cseq */
21574    cseq = get_header(req, "Cseq");
21575    cmd = REQ_OFFSET_TO_STR(req, header[0]);
21576 
21577    /* Must have Cseq */
21578    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
21579       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
21580       error = 1;
21581    }
21582    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
21583       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
21584       error = 1;
21585    }
21586    if (error) {
21587       if (!p->initreq.headers) { /* New call */
21588          pvt_set_needdestroy(p, "no headers");
21589       }
21590       return -1;
21591    }
21592    /* Get the command XXX */
21593 
21594    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
21595    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
21596 
21597    /* Save useragent of the client */
21598    useragent = get_header(req, "User-Agent");
21599    if (!ast_strlen_zero(useragent))
21600       ast_string_field_set(p, useragent, useragent);
21601 
21602    /* Find out SIP method for incoming request */
21603    if (req->method == SIP_RESPONSE) {  /* Response to our request */
21604       /* ignore means "don't do anything with it" but still have to 
21605        * respond appropriately.
21606        * But in this case this is a response already, so we really
21607        * have nothing to do with this message, and even setting the
21608        * ignore flag is pointless.
21609        */
21610       if (ast_strlen_zero(e)) {
21611          return 0;
21612       }
21613       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
21614          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
21615          return 0;
21616       }
21617       if (respid <= 0) {
21618          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
21619          return 0;
21620       }
21621       if (p->ocseq && (p->ocseq < seqno)) {
21622          if (option_debug)
21623             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
21624          return -1;
21625       } else {
21626          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
21627             extract_uri(p, req);
21628          }
21629          handle_response(p, respid, e + len, req, seqno);
21630       }
21631       return 0;
21632    }
21633 
21634    /* New SIP request coming in 
21635       (could be new request in existing SIP dialog as well...) 
21636     */         
21637    
21638    p->method = req->method;   /* Find out which SIP method they are using */
21639    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
21640 
21641    if (p->icseq && (p->icseq > seqno) ) {
21642       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
21643          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
21644       }  else {
21645          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
21646          if (req->method != SIP_ACK)
21647             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21648          return -1;
21649       }
21650    } else if (p->icseq &&
21651          p->icseq == seqno &&
21652          req->method != SIP_ACK &&
21653          (p->method != SIP_CANCEL || p->alreadygone)) {
21654       /* ignore means "don't do anything with it" but still have to 
21655          respond appropriately.  We do this if we receive a repeat of
21656          the last sequence number  */
21657       req->ignore = 1;
21658       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
21659    }
21660       
21661    if (seqno >= p->icseq)
21662       /* Next should follow monotonically (but not necessarily 
21663          incrementally -- thanks again to the genius authors of SIP --
21664          increasing */
21665       p->icseq = seqno;
21666 
21667    /* Find their tag if we haven't got it */
21668    if (ast_strlen_zero(p->theirtag)) {
21669       char tag[128];
21670 
21671       gettag(req, "From", tag, sizeof(tag));
21672       ast_string_field_set(p, theirtag, tag);
21673    }
21674    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
21675 
21676    if (sip_cfg.pedanticsipchecking) {
21677       /* If this is a request packet without a from tag, it's not
21678          correct according to RFC 3261  */
21679       /* Check if this a new request in a new dialog with a totag already attached to it,
21680          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
21681       if (!p->initreq.headers && req->has_to_tag) {
21682          /* If this is a first request and it got a to-tag, it is not for us */
21683          if (!req->ignore && req->method == SIP_INVITE) {
21684             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
21685             /* Will cease to exist after ACK */
21686          } else if (req->method != SIP_ACK) {
21687             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
21688             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21689          } else {
21690             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
21691          }
21692          return res;
21693       }
21694    }
21695 
21696    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
21697       transmit_response(p, "400 Bad request", req);
21698       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21699       return -1;
21700    }
21701 
21702    /* Handle various incoming SIP methods in requests */
21703    switch (p->method) {
21704    case SIP_OPTIONS:
21705       res = handle_request_options(p, req);
21706       break;
21707    case SIP_INVITE:
21708       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
21709       break;
21710    case SIP_REFER:
21711       res = handle_request_refer(p, req, debug, seqno, nounlock);
21712       break;
21713    case SIP_CANCEL:
21714       res = handle_request_cancel(p, req);
21715       break;
21716    case SIP_BYE:
21717       res = handle_request_bye(p, req);
21718       break;
21719    case SIP_MESSAGE:
21720       res = handle_request_message(p, req);
21721       break;
21722    case SIP_SUBSCRIBE:
21723       res = handle_request_subscribe(p, req, sin, seqno, e);
21724       break;
21725    case SIP_REGISTER:
21726       res = handle_request_register(p, req, sin, e);
21727       break;
21728    case SIP_INFO:
21729       if (req->debug)
21730          ast_verbose("Receiving INFO!\n");
21731       if (!req->ignore) 
21732          handle_request_info(p, req);
21733       else  /* if ignoring, transmit response */
21734          transmit_response(p, "200 OK", req);
21735       break;
21736    case SIP_NOTIFY:
21737       res = handle_request_notify(p, req, sin, seqno, e);
21738       break;
21739    case SIP_ACK:
21740       /* Make sure we don't ignore this */
21741       if (seqno == p->pendinginvite) {
21742          p->invitestate = INV_TERMINATED;
21743          p->pendinginvite = 0;
21744          acked = __sip_ack(p, seqno, 1 /* response */, 0);
21745          if (find_sdp(req)) {
21746             if (process_sdp(p, req, SDP_T38_NONE))
21747                return -1;
21748          }
21749          check_pendings(p);
21750       } else if (p->glareinvite == seqno) {
21751          /* handle ack for the 491 pending sent for glareinvite */
21752          p->glareinvite = 0;
21753          acked = __sip_ack(p, seqno, 1, 0);
21754       }
21755       if (!acked) {
21756          /* Got an ACK that did not match anything. Ignore
21757           * silently and restore previous method */
21758          p->method = oldmethod;
21759       }
21760       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
21761          pvt_set_needdestroy(p, "unmatched ACK");
21762       }
21763       break;
21764    default:
21765       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
21766       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
21767          cmd, ast_inet_ntoa(p->sa.sin_addr));
21768       /* If this is some new method, and we don't have a call, destroy it now */
21769       if (!p->initreq.headers) {
21770          pvt_set_needdestroy(p, "unimplemented method");
21771       }
21772       break;
21773    }
21774    return res;
21775 }
21776 
21777 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
21778 {
21779    struct sip_request *req;
21780 
21781    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
21782       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
21783          /* Request failed */
21784          if (option_debug) {
21785             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21786          }
21787       }
21788       ast_free(req);
21789    }
21790 }
21791 
21792 static int scheduler_process_request_queue(const void *data)
21793 {
21794    struct sip_pvt *p = (struct sip_pvt *) data;
21795    int recount = 0;
21796    int nounlock = 0;
21797    int lockretry;
21798 
21799    for (lockretry = 10; lockretry > 0; lockretry--) {
21800       sip_pvt_lock(p);
21801 
21802       /* lock the owner if it has one -- we may need it */
21803       /* because this is deadlock-prone, we need to try and unlock if failed */
21804       if (!p->owner || !ast_channel_trylock(p->owner)) {
21805          break;   /* locking succeeded */
21806       }
21807 
21808       if (lockretry != 1) {
21809          sip_pvt_unlock(p);
21810          /* Sleep for a very short amount of time */
21811          usleep(1);
21812       }
21813    }
21814 
21815    if (!lockretry) {
21816       int retry = !AST_LIST_EMPTY(&p->request_queue);
21817 
21818       /* we couldn't get the owner lock, which is needed to process
21819          the queued requests, so return a non-zero value, which will
21820          cause the scheduler to run this request again later if there
21821          still requests to be processed
21822       */
21823       sip_pvt_unlock(p);
21824       if (!retry) {
21825          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21826       }
21827       return retry;
21828    };
21829 
21830    process_request_queue(p, &recount, &nounlock);
21831    p->request_queue_sched_id = -1;
21832 
21833    if (p->owner && !nounlock) {
21834       ast_channel_unlock(p->owner);
21835    }
21836    sip_pvt_unlock(p);
21837 
21838    if (recount) {
21839       ast_update_use_count();
21840    }
21841 
21842    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
21843 
21844    return 0;
21845 }
21846 
21847 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
21848 {
21849    struct sip_request *newreq;
21850 
21851    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
21852       return -1;
21853    }
21854 
21855    copy_request(newreq, req);
21856    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
21857    if (p->request_queue_sched_id == -1) {
21858       if ((p->request_queue_sched_id = ast_sched_add(sched, 10, scheduler_process_request_queue, dialog_ref(p, "Increment refcount to pass dialog pointer to sched callback"))) == -1) {
21859          dialog_unref(p, "Decrement refcount due to sched_add failure");
21860       }
21861    }
21862 
21863    return 0;
21864 }
21865 
21866 /*! \brief Read data from SIP UDP socket
21867 \note sipsock_read locks the owner channel while we are processing the SIP message
21868 \return 1 on error, 0 on success
21869 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
21870 */
21871 static int sipsock_read(int *id, int fd, short events, void *ignore)
21872 {
21873    struct sip_request req;
21874    struct sockaddr_in sin = { 0, };
21875    int res;
21876    socklen_t len = sizeof(sin);
21877    static char readbuf[65535];
21878 
21879    memset(&req, 0, sizeof(req));
21880    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
21881    if (res < 0) {
21882 #if !defined(__FreeBSD__)
21883       if (errno == EAGAIN)
21884          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
21885       else 
21886 #endif
21887       if (errno != ECONNREFUSED)
21888          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
21889       return 1;
21890    }
21891 
21892    readbuf[res] = '\0';
21893 
21894    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
21895       return 1;
21896    }
21897 
21898    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
21899       return -1;
21900    }
21901 
21902    req.len = res;
21903    req.socket.fd = sipsock;
21904    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
21905    req.socket.tcptls_session  = NULL;
21906    req.socket.port = bindaddr.sin_port;
21907 
21908    handle_request_do(&req, &sin);
21909    if (req.data) {
21910       ast_free(req.data);
21911       req.data = NULL;
21912    }
21913 
21914    return 1;
21915 }
21916 
21917 /*! \brief Handle incoming SIP message - request or response 
21918 
21919    This is used for all transports (udp, tcp and tcp/tls)
21920 */
21921 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
21922 {
21923    struct sip_pvt *p;
21924    int recount = 0;
21925    int nounlock = 0;
21926    int lockretry;
21927 
21928    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
21929       req->debug = 1;
21930    if (sip_cfg.pedanticsipchecking)
21931       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
21932    if (req->debug) {
21933       ast_verbose("\n<--- SIP read from %s:%s:%d --->\n%s\n<------------->\n", 
21934          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
21935          ntohs(sin->sin_port), req->data->str);
21936    }
21937 
21938    if (parse_request(req) == -1) { /* Bad packet, can't parse */
21939       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
21940       return 1;
21941    }
21942    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
21943 
21944    if (req->debug)
21945       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
21946 
21947    if (req->headers < 2) { /* Must have at least two headers */
21948       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
21949       return 1;
21950    }
21951 
21952    /* Process request, with netlock held, and with usual deadlock avoidance */
21953    for (lockretry = 10; lockretry > 0; lockretry--) {
21954       ast_mutex_lock(&netlock);
21955 
21956       /* Find the active SIP dialog or create a new one */
21957       p = find_call(req, sin, req->method);  /* returns p locked */
21958       if (p == NULL) {
21959          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
21960          ast_mutex_unlock(&netlock);
21961          return 1;
21962       }
21963 
21964       copy_socket_data(&p->socket, &req->socket);
21965 
21966       /* Go ahead and lock the owner if it has one -- we may need it */
21967       /* becaues this is deadlock-prone, we need to try and unlock if failed */
21968       if (!p->owner || !ast_channel_trylock(p->owner))
21969          break;   /* locking succeeded */
21970 
21971       if (lockretry != 1) {
21972          sip_pvt_unlock(p);
21973          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
21974          ast_mutex_unlock(&netlock);
21975          /* Sleep for a very short amount of time */
21976          usleep(1);
21977       }
21978    }
21979    p->recv = *sin;
21980 
21981    if (p->do_history) /* This is a request or response, note what it was for */
21982       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
21983 
21984    if (!lockretry) {
21985       if (!queue_request(p, req)) {
21986          /* the request has been queued for later handling */
21987          sip_pvt_unlock(p);
21988          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
21989          ast_mutex_unlock(&netlock);
21990          return 1;
21991       }
21992 
21993       if (p->owner)
21994          ast_log(LOG_ERROR, "Channel lock for %s could not be obtained, and request was unable to be queued.\n", S_OR(p->owner->name, "- no channel name ??? - "));
21995       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
21996       if (req->method != SIP_ACK)
21997          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21998       /* XXX We could add retry-after to make sure they come back */
21999       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
22000       sip_pvt_unlock(p);
22001       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
22002       ast_mutex_unlock(&netlock);
22003       return 1;
22004    }
22005 
22006    /* if there are queued requests on this sip_pvt, process them first, so that everything is
22007       handled in order
22008    */
22009    if (!AST_LIST_EMPTY(&p->request_queue)) {
22010       AST_SCHED_DEL_UNREF(sched, p->request_queue_sched_id, dialog_unref(p, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
22011       process_request_queue(p, &recount, &nounlock);
22012    }
22013 
22014    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
22015       /* Request failed */
22016       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
22017    }
22018       
22019    if (recount)
22020       ast_update_use_count();
22021 
22022    if (p->owner && !nounlock)
22023       ast_channel_unlock(p->owner);
22024    sip_pvt_unlock(p);
22025    ast_mutex_unlock(&netlock);
22026    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
22027    return 1;
22028 }
22029 
22030 /*! \brief Returns the port to use for this socket
22031  *
22032  * \param type The type of transport used
22033  * \param port Port we are checking to see if it's the standard port.
22034  * \note port is expected in host byte order
22035  */
22036 static int sip_standard_port(enum sip_transport type, int port)
22037 {
22038    if (type & SIP_TRANSPORT_TLS)
22039       return port == STANDARD_TLS_PORT;
22040    else
22041       return port == STANDARD_SIP_PORT;
22042 }
22043 
22044 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
22045 {
22046    struct sip_threadinfo *th = obj;
22047    struct sockaddr_in *s = arg;
22048 
22049    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
22050       return CMP_MATCH | CMP_STOP;
22051    }
22052 
22053    return 0;
22054 }
22055 
22056 /*! 
22057  * \brief Find thread for TCP/TLS session (based on IP/Port 
22058  *
22059  * \note This function returns an astobj2 reference
22060  */
22061 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
22062 {
22063    struct sip_threadinfo *th;
22064    struct ast_tcptls_session_instance *tcptls_instance = NULL;
22065 
22066    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
22067       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
22068       ao2_t_ref(th, -1, "decrement ref from callback");
22069    }
22070    return tcptls_instance;
22071 }
22072 
22073 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
22074 static int sip_prepare_socket(struct sip_pvt *p) 
22075 {
22076    struct sip_socket *s = &p->socket;
22077    static const char name[] = "SIP socket";
22078    struct sip_threadinfo *th = NULL;
22079    struct ast_tcptls_session_instance *tcptls_session;
22080    struct ast_tcptls_session_args tmp_ca = {
22081       .name = name,
22082       .accept_fd = -1,
22083    };
22084    struct ast_tcptls_session_args *ca;
22085 
22086    /* check to see if a socket is already active */
22087    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
22088       return s->fd;
22089    }
22090    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
22091          (s->tcptls_session) &&
22092          (s->tcptls_session->fd != -1)) {
22093       return s->tcptls_session->fd;
22094    }
22095 
22096    /*! \todo Check this... This might be wrong, depending on the proxy configuration
22097       If proxy is in "force" mode its correct.
22098     */
22099    if (p->outboundproxy && p->outboundproxy->transport) {
22100       s->type = p->outboundproxy->transport;
22101    }
22102 
22103    if (s->type == SIP_TRANSPORT_UDP) {
22104       s->fd = sipsock;
22105       return s->fd;
22106    }
22107 
22108    /* At this point we are dealing with a TCP/TLS connection
22109     * 1. We need to check to see if a connectin thread exists
22110     *    for this address, if so use that.
22111     * 2. If a thread does not exist for this address, but the tcptls_session
22112     *    exists on the socket, the connection was closed.
22113     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
22114     *    already exists on the socket, create a new one and launch a new thread.
22115     */
22116 
22117    /* 1.  check for existing threads */
22118    tmp_ca.remote_address = *(sip_real_dst(p));
22119    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
22120       s->fd = tcptls_session->fd;
22121       if (s->tcptls_session) {
22122          ao2_ref(s->tcptls_session, -1);
22123          s->tcptls_session = NULL;
22124       }
22125       s->tcptls_session = tcptls_session;
22126       return s->fd;
22127    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
22128    } else if (s->tcptls_session) {
22129       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
22130    }
22131 
22132    /* 3.  Create a new TCP/TLS client connection */
22133    /* create new session arguments for the client connection */
22134    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
22135       !(ca->name = ast_strdup(name))) {
22136       goto create_tcptls_session_fail;
22137    }
22138    ca->accept_fd = -1;
22139    ca->remote_address = *(sip_real_dst(p));
22140    /* if type is TLS, we need to create a tls cfg for this session arg */
22141    if (s->type == SIP_TRANSPORT_TLS) {
22142       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
22143          goto create_tcptls_session_fail;
22144       }
22145       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
22146 
22147       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
22148          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
22149          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
22150          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
22151 
22152          goto create_tcptls_session_fail;
22153       }
22154 
22155       /* this host is used as the common name in ssl/tls */
22156       if (!ast_strlen_zero(p->tohost)) {
22157          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
22158       }
22159    }
22160    /* Create a client connection for address, this does not start the connection, just sets it up. */
22161    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
22162       goto create_tcptls_session_fail;
22163    }
22164 
22165    s->fd = s->tcptls_session->fd;
22166 
22167    /* client connections need to have the sip_threadinfo object created before
22168     * the thread is detached.  This ensures the alert_pipe is up before it will
22169     * be used.  Note that this function links the new threadinfo object into the
22170     * threadt container. */
22171    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
22172       goto create_tcptls_session_fail;
22173 
22174    }
22175 
22176    /* Give the new thread a reference to the tcptls_session */
22177    ao2_ref(s->tcptls_session, +1);
22178 
22179    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
22180       ast_debug(1, "Unable to launch '%s'.", ca->name);
22181       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
22182       goto create_tcptls_session_fail;
22183    }
22184 
22185    return s->fd;
22186 
22187 create_tcptls_session_fail:
22188    if (ca) {
22189       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
22190    }
22191    if (s->tcptls_session) {
22192       close(tcptls_session->fd);
22193       s->fd = tcptls_session->fd = -1;
22194       ao2_ref(s->tcptls_session, -1);
22195       s->tcptls_session = NULL;
22196    }
22197    if (th) {
22198       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
22199    }
22200 
22201    return -1;
22202 }
22203 
22204 /*!
22205  * \brief Small function to parse a config line for a host with a transport
22206  *        i.e. tls://www.google.com:8056
22207  */
22208 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
22209 {
22210    char *port;
22211 
22212    if ((*hostname = strstr(line, "://"))) {
22213       *hostname += 3;
22214 
22215       if (!strncasecmp(line, "tcp", 3))
22216          *transport = SIP_TRANSPORT_TCP;
22217       else if (!strncasecmp(line, "tls", 3))
22218          *transport = SIP_TRANSPORT_TLS;
22219       else if (!strncasecmp(line, "udp", 3))
22220          *transport = SIP_TRANSPORT_UDP;
22221       else
22222          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
22223    } else {
22224       *hostname = line;
22225       *transport = SIP_TRANSPORT_UDP;
22226    }
22227 
22228    if ((line = strrchr(*hostname, '@')))
22229       line++;
22230    else
22231       line = *hostname;
22232 
22233    if ((port = strrchr(line, ':'))) {
22234       *port++ = '\0';
22235 
22236       if (!sscanf(port, "%5u", portnum)) {
22237          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
22238          port = NULL;
22239       }
22240    }
22241 
22242    if (!port) {
22243       if (*transport & SIP_TRANSPORT_TLS) {
22244          *portnum = STANDARD_TLS_PORT;
22245       } else {
22246          *portnum = STANDARD_SIP_PORT;
22247       }
22248    }
22249 
22250    return 0;
22251 }
22252 
22253 /*!
22254  * \brief Get cached MWI info
22255  * \retval 0 At least one message is waiting
22256  * \retval 1 no messages waiting
22257  */
22258 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
22259 {
22260    struct sip_mailbox *mailbox;
22261 
22262    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
22263       struct ast_event *event;
22264       event = ast_event_get_cached(AST_EVENT_MWI,
22265          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
22266          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
22267          AST_EVENT_IE_END);
22268       if (!event)
22269          continue;
22270       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22271       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22272       ast_event_destroy(event);
22273    }
22274 
22275    return (*new || *old) ? 0 : 1;
22276 }
22277 
22278 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
22279 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
22280 {
22281    /* Called with peerl lock, but releases it */
22282    struct sip_pvt *p;
22283    int newmsgs = 0, oldmsgs = 0;
22284 
22285    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
22286       return 0;
22287 
22288    /* Do we have an IP address? If not, skip this peer */
22289    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
22290       return 0;
22291 
22292    if (event) {
22293       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
22294       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
22295    } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
22296       /* got it!  Don't keep looking. */
22297    } else if (cache_only) {
22298       return 0;
22299    } else { /* Fall back to manually checking the mailbox */
22300       struct ast_str *mailbox_str = ast_str_alloca(512);
22301       peer_mailboxes_to_str(&mailbox_str, peer);
22302       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
22303    }
22304    
22305    if (peer->mwipvt) {
22306       /* Base message on subscription */
22307       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
22308    } else {
22309       /* Build temporary dialog for this message */
22310       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
22311          return -1;
22312       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
22313        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
22314        * the peer's socket information to the sip_pvt we just allocated
22315        */
22316       set_socket_transport(&p->socket, 0);
22317       if (create_addr_from_peer(p, peer)) {
22318          /* Maybe they're not registered, etc. */
22319          dialog_unlink_all(p, TRUE, TRUE);
22320          dialog_unref(p, "unref dialog p just created via sip_alloc");
22321          /* sip_destroy(p); */
22322          return 0;
22323       }
22324       /* Recalculate our side, and recalculate Call ID */
22325       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22326       build_via(p);
22327       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22328       build_callid_pvt(p);
22329       ao2_t_link(dialogs, p, "Linking in under new name");
22330       /* Destroy this session after 32 secs */
22331       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22332    }
22333 
22334    /* Send MWI */
22335    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22336    /* the following will decrement the refcount on p as it finishes */
22337    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
22338    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
22339    return 0;
22340 }
22341 
22342 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
22343 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
22344 {
22345    /* If we have no RTP or no active owner, no need to check timers */
22346    if (!dialog->rtp || !dialog->owner)
22347       return;
22348    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
22349 
22350    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
22351       return;
22352 
22353    /* If the call is involved in a T38 fax session do not check RTP timeout */
22354    if (dialog->t38.state == T38_ENABLED)
22355       return;
22356 
22357    /* If we have no timers set, return now */
22358    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
22359       return;
22360 
22361    /* Check AUDIO RTP keepalives */
22362    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
22363           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
22364       /* Need to send an empty RTP packet */
22365       dialog->lastrtptx = time(NULL);
22366       ast_rtp_sendcng(dialog->rtp, 0);
22367    }
22368 
22369    /*! \todo Check video RTP keepalives
22370 
22371       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
22372       for video? It really does belong to the RTP structure.
22373    */
22374 
22375    /* Check AUDIO RTP timers */
22376    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
22377           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
22378 
22379       /* Might be a timeout now -- see if we're on hold */
22380       struct sockaddr_in sin;
22381       ast_rtp_get_peer(dialog->rtp, &sin);
22382       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
22383            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
22384          /* Needs a hangup */
22385          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
22386             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
22387                sip_pvt_unlock(dialog);
22388                usleep(1);
22389                sip_pvt_lock(dialog);
22390             }
22391             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
22392                dialog->owner->name, (long) (t - dialog->lastrtprx));
22393             /* Issue a softhangup */
22394             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
22395             ast_channel_unlock(dialog->owner);
22396             /* forget the timeouts for this call, since a hangup
22397                has already been requested and we don't want to
22398                repeatedly request hangups
22399             */
22400             ast_rtp_set_rtptimeout(dialog->rtp, 0);
22401             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
22402             if (dialog->vrtp) {
22403                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
22404                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
22405             }
22406          }
22407       }
22408    }
22409 }
22410 
22411 /*! \brief The SIP monitoring thread 
22412 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
22413    (and thus do not have a separate thread) indefinitely 
22414 */
22415 static void *do_monitor(void *data)
22416 {
22417    int res;
22418    time_t t;
22419    int reloading;
22420 
22421    /* Add an I/O event to our SIP UDP socket */
22422    if (sipsock > -1) 
22423       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22424 
22425    /* From here on out, we die whenever asked */
22426    for(;;) {
22427       /* Check for a reload request */
22428       ast_mutex_lock(&sip_reload_lock);
22429       reloading = sip_reloading;
22430       sip_reloading = FALSE;
22431       ast_mutex_unlock(&sip_reload_lock);
22432       if (reloading) {
22433          ast_verb(1, "Reloading SIP\n");
22434          sip_do_reload(sip_reloadreason);
22435 
22436          /* Change the I/O fd of our UDP socket */
22437          if (sipsock > -1) {
22438             if (sipsock_read_id)
22439                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
22440             else
22441                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
22442          } else if (sipsock_read_id) {
22443             ast_io_remove(io, sipsock_read_id);
22444             sipsock_read_id = NULL;
22445          }
22446       }
22447 
22448       /* Check for dialogs needing to be killed */
22449       t = time(NULL);
22450       /* don't scan the dialogs list if it hasn't been a reasonable period
22451          of time since the last time we did it (when MWI is being sent, we can
22452          get back to this point every millisecond or less)
22453       */
22454       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
22455             "callback to remove dialogs w/needdestroy");
22456 
22457       /* the old methodology would be to restart the search for dialogs to delete with every 
22458          dialog that was found and destroyed, probably because the list contents would change,
22459          so we'd need to restart. This isn't the best thing to do with callbacks. */
22460 
22461       /* XXX TODO The scheduler usage in this module does not have sufficient 
22462        * synchronization being done between running the scheduler and places 
22463        * scheduling tasks.  As it is written, any scheduled item may not run 
22464        * any sooner than about  1 second, regardless of whether a sooner time 
22465        * was asked for. */
22466 
22467       pthread_testcancel();
22468       /* Wait for sched or io */
22469       res = ast_sched_wait(sched);
22470       if ((res < 0) || (res > 1000))
22471          res = 1000;
22472       res = ast_io_wait(io, res);
22473       if (res > 20)
22474          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
22475       ast_mutex_lock(&monlock);
22476       res = ast_sched_runq(sched);
22477       if (res >= 20)
22478          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
22479       ast_mutex_unlock(&monlock);
22480    }
22481 
22482    /* Never reached */
22483    return NULL;
22484 }
22485 
22486 /*! \brief Start the channel monitor thread */
22487 static int restart_monitor(void)
22488 {
22489    /* If we're supposed to be stopped -- stay stopped */
22490    if (monitor_thread == AST_PTHREADT_STOP)
22491       return 0;
22492    ast_mutex_lock(&monlock);
22493    if (monitor_thread == pthread_self()) {
22494       ast_mutex_unlock(&monlock);
22495       ast_log(LOG_WARNING, "Cannot kill myself\n");
22496       return -1;
22497    }
22498    if (monitor_thread != AST_PTHREADT_NULL) {
22499       /* Wake up the thread */
22500       pthread_kill(monitor_thread, SIGURG);
22501    } else {
22502       /* Start a new monitor */
22503       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
22504          ast_mutex_unlock(&monlock);
22505          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
22506          return -1;
22507       }
22508    }
22509    ast_mutex_unlock(&monlock);
22510    return 0;
22511 }
22512 
22513 
22514 /*! \brief Session-Timers: Restart session timer */
22515 static void restart_session_timer(struct sip_pvt *p)
22516 {
22517    if (!p->stimer) {
22518       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
22519       return;
22520    }
22521 
22522    if (p->stimer->st_active == TRUE) {
22523       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22524             dialog_unref(p, "Removing session timer ref"));
22525       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22526       start_session_timer(p);
22527    }
22528 }
22529 
22530 
22531 /*! \brief Session-Timers: Stop session timer */
22532 static void stop_session_timer(struct sip_pvt *p)
22533 {
22534    if (!p->stimer) {
22535       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
22536       return;
22537    }
22538 
22539    if (p->stimer->st_active == TRUE) {
22540       p->stimer->st_active = FALSE;
22541       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
22542             dialog_unref(p, "removing session timer ref"));
22543       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
22544    }
22545 }
22546 
22547 
22548 /*! \brief Session-Timers: Start session timer */
22549 static void start_session_timer(struct sip_pvt *p)
22550 {
22551    if (!p->stimer) {
22552       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
22553       return;
22554    }
22555 
22556    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
22557          dialog_ref(p, "adding session timer ref"));
22558    if (p->stimer->st_schedid < 0) {
22559       dialog_unref(p, "removing session timer ref");
22560       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
22561    }
22562    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
22563 }
22564 
22565 
22566 /*! \brief Session-Timers: Process session refresh timeout event */
22567 static int proc_session_timer(const void *vp)
22568 {
22569    struct sip_pvt *p = (struct sip_pvt *) vp;
22570    int sendreinv = FALSE;
22571    int res = 0;
22572 
22573    if (!p->stimer) {
22574       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
22575       goto return_unref;
22576    }
22577 
22578    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
22579 
22580    if (!p->owner) {
22581       goto return_unref;
22582    }
22583 
22584    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
22585       goto return_unref;
22586    }
22587 
22588    switch (p->stimer->st_ref) {
22589    case SESSION_TIMER_REFRESHER_UAC:
22590       if (p->outgoing_call == TRUE) {
22591          sendreinv = TRUE;
22592       }
22593       break;
22594    case SESSION_TIMER_REFRESHER_UAS:
22595       if (p->outgoing_call != TRUE) {
22596          sendreinv = TRUE;
22597       }
22598       break;
22599    default:
22600       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
22601       goto return_unref;
22602    }
22603 
22604    if (sendreinv == TRUE) {
22605       res = 1;
22606       transmit_reinvite_with_sdp(p, FALSE, TRUE);
22607    } else {
22608       p->stimer->st_expirys++;
22609       if (p->stimer->st_expirys >= 2) {
22610          if (p->stimer->quit_flag) {
22611             goto return_unref;
22612          }
22613          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
22614          sip_pvt_lock(p);
22615          while (p->owner && ast_channel_trylock(p->owner)) {
22616             sip_pvt_unlock(p);
22617             usleep(1);
22618             if (p->stimer && p->stimer->quit_flag) {
22619                goto return_unref;
22620             }
22621             sip_pvt_lock(p);
22622          }
22623 
22624          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22625          ast_channel_unlock(p->owner);
22626          sip_pvt_unlock(p);
22627       }
22628    }
22629 
22630 return_unref:
22631    if (!res) {
22632       /* An error occurred.  Stop session timer processing */
22633       if (p->stimer) {
22634          p->stimer->st_schedid = -1;
22635          stop_session_timer(p);
22636       }
22637 
22638       /* If we are not asking to be rescheduled, then we need to release our
22639        * reference to the dialog. */
22640       dialog_unref(p, "removing session timer ref");
22641    }
22642 
22643    return res;
22644 }
22645 
22646 
22647 /*! \brief Session-Timers: Function for parsing Min-SE header */
22648 int parse_minse (const char *p_hdrval, int *const p_interval)
22649 {
22650    if (ast_strlen_zero(p_hdrval)) {
22651       ast_log(LOG_WARNING, "Null Min-SE header\n");
22652       return -1;
22653    }
22654 
22655    *p_interval = 0;
22656    p_hdrval = ast_skip_blanks(p_hdrval);
22657    if (!sscanf(p_hdrval, "%30d", p_interval)) {
22658       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22659       return -1;
22660    }
22661 
22662    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
22663    return 0;
22664 }
22665 
22666 
22667 /*! \brief Session-Timers: Function for parsing Session-Expires header */
22668 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
22669 {
22670    char *p_token;
22671    int  ref_idx;
22672    char *p_se_hdr;
22673 
22674    if (ast_strlen_zero(p_hdrval)) {
22675       ast_log(LOG_WARNING, "Null Session-Expires header\n");
22676       return -1;
22677    }
22678 
22679    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
22680    *p_interval = 0;
22681 
22682    p_se_hdr = ast_strdupa(p_hdrval);
22683    p_se_hdr = ast_skip_blanks(p_se_hdr);
22684 
22685    while ((p_token = strsep(&p_se_hdr, ";"))) {
22686       p_token = ast_skip_blanks(p_token);
22687       if (!sscanf(p_token, "%30d", p_interval)) {
22688          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
22689          return -1;
22690       }
22691 
22692       ast_debug(2, "Session-Expires: %d\n", *p_interval);
22693 
22694       if (!p_se_hdr)
22695          continue;
22696 
22697       p_se_hdr = ast_skip_blanks(p_se_hdr);
22698       ref_idx = strlen("refresher=");
22699       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
22700          p_se_hdr += ref_idx;
22701          p_se_hdr = ast_skip_blanks(p_se_hdr);
22702 
22703          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
22704             *p_ref = SESSION_TIMER_REFRESHER_UAC;
22705             ast_debug(2, "Refresher: UAC\n");
22706          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
22707             *p_ref = SESSION_TIMER_REFRESHER_UAS;
22708             ast_debug(2, "Refresher: UAS\n");
22709          } else {
22710             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
22711             return -1;
22712          }
22713          break;
22714       }
22715    }
22716    return 0;
22717 }
22718 
22719 
22720 /*! \brief Handle 422 response to INVITE with session-timer requested
22721 
22722    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
22723    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
22724    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
22725    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
22726    header that comes back in 422 and sends a new INVITE accordingly. */
22727 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
22728 {
22729    int rtn;
22730    const char *p_hdrval;
22731    int minse;
22732 
22733    p_hdrval = get_header(rsp, "Min-SE");
22734    if (ast_strlen_zero(p_hdrval)) {
22735       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
22736       return;
22737    }
22738    rtn = parse_minse(p_hdrval, &minse);
22739    if (rtn != 0) {
22740       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
22741       return;
22742    }
22743    p->stimer->st_interval = minse;
22744    transmit_invite(p, SIP_INVITE, 1, 2); 
22745 }
22746 
22747 
22748 /*! \brief Get Max or Min SE (session timer expiry)
22749  * \param p pointer to the SIP dialog 
22750  * \param max if true, get max se, otherwise min se
22751 */
22752 int st_get_se(struct sip_pvt *p, int max)
22753 {
22754    if (max == TRUE) {
22755       if (p->stimer->st_cached_max_se) {
22756          return p->stimer->st_cached_max_se;
22757       } else if (p->peername) {
22758          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22759          if (pp) {
22760             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
22761             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
22762             return (p->stimer->st_cached_max_se);
22763          }
22764       }
22765       p->stimer->st_cached_max_se = global_max_se;
22766       return (p->stimer->st_cached_max_se);
22767    } else {
22768       if (p->stimer->st_cached_min_se) {
22769          return p->stimer->st_cached_min_se;
22770       } else if (p->peername) {
22771          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22772          if (pp) {
22773             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
22774             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
22775             return (p->stimer->st_cached_min_se);
22776          }
22777       }
22778       p->stimer->st_cached_min_se = global_min_se;
22779       return (p->stimer->st_cached_min_se);
22780    }
22781 }
22782 
22783 
22784 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
22785  * \param p pointer to the SIP dialog 
22786 */
22787 enum st_refresher st_get_refresher(struct sip_pvt *p)
22788 {
22789    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
22790       return p->stimer->st_cached_ref;
22791 
22792    if (p->peername) {
22793       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22794       if (pp) {
22795          p->stimer->st_cached_ref = pp->stimer.st_ref;
22796          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
22797          return pp->stimer.st_ref;
22798       }
22799    }
22800    
22801    p->stimer->st_cached_ref = global_st_refresher;
22802    return global_st_refresher;
22803 }
22804 
22805 
22806 /*! \brief Get the session-timer mode 
22807  * \param p pointer to the SIP dialog 
22808 */
22809 enum st_mode st_get_mode(struct sip_pvt *p)
22810 {
22811    if (!p->stimer) 
22812       sip_st_alloc(p);
22813 
22814    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
22815       return p->stimer->st_cached_mode;
22816 
22817    if (p->peername) {
22818       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
22819       if (pp) {
22820          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
22821          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
22822          return pp->stimer.st_mode_oper;
22823       }
22824    }
22825 
22826    p->stimer->st_cached_mode = global_st_mode;
22827    return global_st_mode;
22828 }
22829 
22830 
22831 /*! \brief React to lack of answer to Qualify poke */
22832 static int sip_poke_noanswer(const void *data)
22833 {
22834    struct sip_peer *peer = (struct sip_peer *)data;
22835    
22836    peer->pokeexpire = -1;
22837 
22838    if (peer->lastms > -1) {
22839       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
22840       if (sip_cfg.peer_rtupdate) {
22841          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
22842       }
22843       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
22844       if (sip_cfg.regextenonqualify) {
22845          register_peer_exten(peer, FALSE);
22846       }
22847    }
22848 
22849    if (peer->call) {
22850       dialog_unlink_all(peer->call, TRUE, TRUE);
22851       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22852       /* peer->call = sip_destroy(peer->call);*/
22853    }
22854    
22855    peer->lastms = -1;
22856    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
22857 
22858    /* Try again quickly */
22859    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
22860          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
22861          unref_peer(_data, "removing poke peer ref"),
22862          unref_peer(peer, "removing poke peer ref"),
22863          ref_peer(peer, "adding poke peer ref"));
22864 
22865    /* Release the ref held by the running scheduler entry */
22866    unref_peer(peer, "release peer poke noanswer ref");
22867 
22868    return 0;
22869 }
22870 
22871 /*! \brief Check availability of peer, also keep NAT open
22872 \note This is done with 60 seconds between each ping,
22873    unless forced by cli or manager. If peer is unreachable,
22874    we check every 10th second by default. 
22875 */
22876 static int sip_poke_peer(struct sip_peer *peer, int force)
22877 {
22878    struct sip_pvt *p;
22879    int xmitres = 0;
22880    
22881    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
22882       /* IF we have no IP, or this isn't to be monitored, return
22883         immediately after clearing things out */
22884       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22885             unref_peer(peer, "removing poke peer ref"));
22886       
22887       peer->lastms = 0;
22888       if (peer->call) {
22889          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22890       }
22891       return 0;
22892    }
22893    if (peer->call) {
22894       if (sipdebug) {
22895          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
22896       }
22897       dialog_unlink_all(peer->call, TRUE, TRUE);
22898       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
22899       /* peer->call = sip_destroy(peer->call); */
22900    }
22901    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
22902       return -1;
22903    }
22904    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
22905    
22906    p->sa = peer->addr;
22907    p->recv = peer->addr;
22908    copy_socket_data(&p->socket, &peer->socket);
22909    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
22910    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
22911 
22912    /* Send OPTIONs to peer's fullcontact */
22913    if (!ast_strlen_zero(peer->fullcontact))
22914       ast_string_field_set(p, fullcontact, peer->fullcontact);
22915 
22916    if (!ast_strlen_zero(peer->tohost))
22917       ast_string_field_set(p, tohost, peer->tohost);
22918    else
22919       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
22920 
22921    /* Recalculate our side, and recalculate Call ID */
22922    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22923    build_via(p);
22924    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22925    build_callid_pvt(p);
22926    ao2_t_link(dialogs, p, "Linking in under new name");
22927 
22928    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
22929          unref_peer(peer, "removing poke peer ref"));
22930    
22931    if (p->relatedpeer)
22932       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
22933    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
22934    ast_set_flag(&p->flags[0], SIP_OUTGOING);
22935 #ifdef VOCAL_DATA_HACK
22936    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
22937    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
22938 #else
22939    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
22940 #endif
22941    peer->ps = ast_tvnow();
22942    if (xmitres == XMIT_ERROR) {
22943       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
22944    } else if (!force) {
22945       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
22946             unref_peer(_data, "removing poke peer ref"),
22947             unref_peer(peer, "removing poke peer ref"),
22948             ref_peer(peer, "adding poke peer ref"));
22949    }
22950    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
22951    return 0;
22952 }
22953 
22954 /*! \brief Part of PBX channel interface
22955 \note
22956 \par  Return values:---
22957 
22958    If we have qualify on and the device is not reachable, regardless of registration
22959    state we return AST_DEVICE_UNAVAILABLE
22960 
22961    For peers with call limit:
22962       - not registered        AST_DEVICE_UNAVAILABLE
22963       - registered, no call         AST_DEVICE_NOT_INUSE
22964       - registered, active calls    AST_DEVICE_INUSE
22965       - registered, call limit reached AST_DEVICE_BUSY
22966       - registered, onhold       AST_DEVICE_ONHOLD
22967       - registered, ringing         AST_DEVICE_RINGING
22968 
22969    For peers without call limit:
22970       - not registered        AST_DEVICE_UNAVAILABLE
22971       - registered            AST_DEVICE_NOT_INUSE
22972       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
22973    
22974    Peers that does not have a known call and can't be reached by OPTIONS
22975       - unreachable           AST_DEVICE_UNAVAILABLE
22976 
22977    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
22978    out a state by walking the channel list.
22979 
22980    The queue system (\ref app_queue.c) treats a member as "active"
22981    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
22982 
22983    When placing a call to the queue member, queue system sets a member to busy if
22984    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
22985 
22986 */
22987 static int sip_devicestate(void *data)
22988 {
22989    char *host;
22990    char *tmp;
22991    struct sip_peer *p;
22992 
22993    int res = AST_DEVICE_INVALID;
22994 
22995    /* make sure data is not null. Maybe unnecessary, but better be safe */
22996    host = ast_strdupa(data ? data : "");
22997    if ((tmp = strchr(host, '@')))
22998       host = tmp + 1;
22999 
23000    ast_debug(3, "Checking device state for peer %s\n", host);
23001 
23002    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
23003     * is because when a peer tries to autoexpire, the last thing it does is to
23004     * queue up an event telling the system that the devicestate has changed
23005     * (presumably to unavailable).  If we ask for a realtime peer here, this would
23006     * load it BACK into memory, thus defeating the point of trying to clear dead
23007     * hosts out of memory.
23008     */
23009    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
23010       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
23011          /* we have an address for the peer */
23012       
23013          /* Check status in this order
23014             - Hold
23015             - Ringing
23016             - Busy (enforced only by call limit)
23017             - Inuse (we have a call)
23018             - Unreachable (qualify)
23019             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
23020             for registered devices */
23021 
23022          if (p->onHold)
23023             /* First check for hold or ring states */
23024             res = AST_DEVICE_ONHOLD;
23025          else if (p->inRinging) {
23026             if (p->inRinging == p->inUse)
23027                res = AST_DEVICE_RINGING;
23028             else
23029                res = AST_DEVICE_RINGINUSE;
23030          } else if (p->call_limit && (p->inUse == p->call_limit))
23031             /* check call limit */
23032             res = AST_DEVICE_BUSY;
23033          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
23034             /* We're forcing busy before we've reached the call limit */
23035             res = AST_DEVICE_BUSY;
23036          else if (p->call_limit && p->inUse)
23037             /* Not busy, but we do have a call */
23038             res = AST_DEVICE_INUSE;
23039          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
23040             /* We don't have a call. Are we reachable at all? Requires qualify= */
23041             res = AST_DEVICE_UNAVAILABLE;
23042          else  /* Default reply if we're registered and have no other data */
23043             res = AST_DEVICE_NOT_INUSE;
23044       } else {
23045          /* there is no address, it's unavailable */
23046          res = AST_DEVICE_UNAVAILABLE;
23047       }
23048       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
23049    } else {
23050       res = AST_DEVICE_UNKNOWN;
23051    }
23052 
23053    return res;
23054 }
23055 
23056 /*! \brief PBX interface function -build SIP pvt structure 
23057  * SIP calls initiated by the PBX arrive here. 
23058  *
23059  * \verbatim   
23060  *    SIP Dial string syntax
23061  *    SIP/exten@host!dnid
23062  * or SIP/host/exten!dnid
23063  * or SIP/host!dnid
23064  * \endverbatim
23065 */
23066 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
23067 {
23068    struct sip_pvt *p;
23069    struct ast_channel *tmpc = NULL;
23070    char *ext = NULL, *host;
23071    char tmp[256];
23072    char *dest = data;
23073    char *dnid;
23074    char *secret = NULL;
23075    char *md5secret = NULL;
23076    char *authname = NULL;
23077    char *trans = NULL;
23078    enum sip_transport transport = 0;
23079    int oldformat = format;
23080 
23081    /* mask request with some set of allowed formats.
23082     * XXX this needs to be fixed.
23083     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
23084     * unclear what to use here. We have global_capabilities, which is
23085     * configured from sip.conf, and sip_tech.capabilities, which is
23086     * hardwired to all audio formats.
23087     */
23088    format &= AST_FORMAT_AUDIO_MASK;
23089    if (!format) {
23090       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(global_capability));
23091       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
23092       return NULL;
23093    }
23094    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
23095 
23096    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
23097       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
23098       *cause = AST_CAUSE_SWITCH_CONGESTION;
23099       return NULL;
23100    }
23101 
23102    p->outgoing_call = TRUE;
23103 
23104    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
23105       dialog_unlink_all(p, TRUE, TRUE);
23106       dialog_unref(p, "unref dialog p from mem fail");
23107       /* sip_destroy(p); */
23108       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
23109       *cause = AST_CAUSE_SWITCH_CONGESTION;
23110       return NULL;
23111    }
23112 
23113    /* Save the destination, the SIP dial string */
23114    ast_copy_string(tmp, dest, sizeof(tmp));
23115 
23116 
23117    /* Find DNID and take it away */
23118    dnid = strchr(tmp, '!');
23119    if (dnid != NULL) {
23120       *dnid++ = '\0';
23121       ast_string_field_set(p, todnid, dnid);
23122    }
23123 
23124    /* Find at sign - @ */
23125    host = strchr(tmp, '@');
23126    if (host) {
23127       *host++ = '\0';
23128       ext = tmp;
23129       secret = strchr(ext, ':');
23130    }
23131    if (secret) {
23132       *secret++ = '\0';
23133       md5secret = strchr(secret, ':');
23134    }
23135    if (md5secret) {
23136       *md5secret++ = '\0';
23137       authname = strchr(md5secret, ':');
23138    }
23139    if (authname) {
23140       *authname++ = '\0';
23141       trans = strchr(authname, ':');
23142    }
23143    if (trans) {
23144       *trans++ = '\0';
23145       if (!strcasecmp(trans, "tcp"))
23146          transport = SIP_TRANSPORT_TCP;
23147       else if (!strcasecmp(trans, "tls"))
23148          transport = SIP_TRANSPORT_TLS;
23149       else {
23150          if (strcasecmp(trans, "udp"))
23151             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
23152          transport = SIP_TRANSPORT_UDP;
23153       }
23154    } else { /* use default */
23155       transport = SIP_TRANSPORT_UDP;
23156    }
23157 
23158    if (!host) {
23159       ext = strchr(tmp, '/');
23160       if (ext) 
23161          *ext++ = '\0';
23162       host = tmp;
23163    }
23164 
23165    set_socket_transport(&p->socket, transport);
23166 
23167    /* We now have 
23168       host = peer name, DNS host name or DNS domain (for SRV) 
23169       ext = extension (user part of URI)
23170       dnid = destination of the call (applies to the To: header)
23171    */
23172    if (create_addr(p, host, NULL, 1)) {
23173       *cause = AST_CAUSE_UNREGISTERED;
23174       ast_debug(3, "Cant create SIP call - target device not registered\n");
23175       dialog_unlink_all(p, TRUE, TRUE);
23176       dialog_unref(p, "unref dialog p UNREGISTERED");
23177       /* sip_destroy(p); */
23178       return NULL;
23179    }
23180    if (ast_strlen_zero(p->peername) && ext)
23181       ast_string_field_set(p, peername, ext);
23182    /* Recalculate our side, and recalculate Call ID */
23183    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
23184    build_via(p);
23185    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
23186    build_callid_pvt(p);
23187    ao2_t_link(dialogs, p, "Linking in under new name");
23188    
23189    /* We have an extension to call, don't use the full contact here */
23190    /* This to enable dialing registered peers with extension dialling,
23191       like SIP/peername/extension   
23192       SIP/peername will still use the full contact 
23193     */
23194    if (ext) {
23195       ast_string_field_set(p, username, ext);
23196       ast_string_field_set(p, fullcontact, NULL);
23197    }
23198    if (secret && !ast_strlen_zero(secret))
23199       ast_string_field_set(p, peersecret, secret);
23200 
23201    if (md5secret && !ast_strlen_zero(md5secret))
23202       ast_string_field_set(p, peermd5secret, md5secret);
23203 
23204    if (authname && !ast_strlen_zero(authname))
23205       ast_string_field_set(p, authname, authname);
23206 #if 0
23207    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
23208 #endif
23209    p->prefcodec = oldformat;           /* Format for this call */
23210    p->jointcapability = oldformat;
23211    sip_pvt_lock(p);
23212    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
23213    if (sip_cfg.callevents)
23214       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23215          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23216          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
23217    sip_pvt_unlock(p);
23218    if (!tmpc) {
23219       dialog_unlink_all(p, TRUE, TRUE);
23220       /* sip_destroy(p); */
23221    }
23222    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
23223    ast_update_use_count();
23224    restart_monitor();
23225    return tmpc;
23226 }
23227 
23228 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
23229 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
23230 {
23231    if (ast_strlen_zero(value))
23232       return;
23233 
23234    if (!ast_false(value)) {
23235       char buf[64];
23236       char *word, *next;
23237 
23238       ast_copy_string(buf, value, sizeof(buf));
23239       next = buf;
23240       while ((word = strsep(&next, ","))) {
23241          if (!strcasecmp(word, "port"))
23242             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
23243          else if (!strcasecmp(word, "invite"))
23244             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
23245          else
23246             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
23247       }
23248    }
23249 }
23250 
23251 /*!
23252   \brief Handle T.38 configuration options common to users and peers
23253   \returns non-zero if any config options were handled, zero otherwise
23254 */
23255 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
23256                int *maxdatagram)
23257 {
23258    int res = 1;
23259 
23260    if (!strcasecmp(v->name, "t38pt_udptl")) {
23261       char *buf = ast_strdupa(v->value);
23262       char *word, *next = buf;
23263 
23264       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
23265 
23266       while ((word = strsep(&next, ","))) {
23267          if (ast_true(word) || !strcasecmp(word, "fec")) {
23268             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23269             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
23270          } else if (!strcasecmp(word, "redundancy")) {
23271             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23272             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
23273          } else if (!strcasecmp(word, "none")) {
23274             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
23275             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
23276          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
23277             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
23278                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
23279                *maxdatagram = global_t38_maxdatagram;
23280             }
23281          }
23282       }
23283    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
23284       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
23285       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
23286    } else {
23287       res = 0;
23288    }
23289 
23290    return res;
23291 }
23292 
23293 /*!
23294   \brief Handle flag-type options common to configuration of devices - peers
23295   \param flags array of two struct ast_flags
23296   \param mask array of two struct ast_flags
23297   \param v linked list of config variables to process
23298   \returns non-zero if any config options were handled, zero otherwise
23299 */
23300 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
23301 {
23302    int res = 1;
23303 
23304    if (!strcasecmp(v->name, "trustrpid")) {
23305       ast_set_flag(&mask[0], SIP_TRUSTRPID);
23306       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
23307    } else if (!strcasecmp(v->name, "sendrpid")) {
23308       ast_set_flag(&mask[0], SIP_SENDRPID);
23309       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
23310    } else if (!strcasecmp(v->name, "g726nonstandard")) {
23311       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
23312       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
23313    } else if (!strcasecmp(v->name, "useclientcode")) {
23314       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
23315       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
23316    } else if (!strcasecmp(v->name, "dtmfmode")) {
23317       ast_set_flag(&mask[0], SIP_DTMF);
23318       ast_clear_flag(&flags[0], SIP_DTMF);
23319       if (!strcasecmp(v->value, "inband"))
23320          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
23321       else if (!strcasecmp(v->value, "rfc2833"))
23322          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23323       else if (!strcasecmp(v->value, "info"))
23324          ast_set_flag(&flags[0], SIP_DTMF_INFO);
23325       else if (!strcasecmp(v->value, "shortinfo"))
23326          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
23327       else if (!strcasecmp(v->value, "auto"))
23328          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
23329       else {
23330          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
23331          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
23332       }
23333    } else if (!strcasecmp(v->name, "nat")) {
23334       ast_set_flag(&mask[0], SIP_NAT);
23335       ast_clear_flag(&flags[0], SIP_NAT);
23336       if (!strcasecmp(v->value, "never"))
23337          ast_set_flag(&flags[0], SIP_NAT_NEVER);
23338       else if (!strcasecmp(v->value, "route"))
23339          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
23340       else if (ast_true(v->value))
23341          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
23342       else
23343          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
23344    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
23345       ast_set_flag(&mask[0], SIP_REINVITE);
23346       ast_clear_flag(&flags[0], SIP_REINVITE);
23347       if (ast_true(v->value)) {
23348          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
23349       } else if (!ast_false(v->value)) {
23350          char buf[64];
23351          char *word, *next = buf;
23352 
23353          ast_copy_string(buf, v->value, sizeof(buf));
23354          while ((word = strsep(&next, ","))) {
23355             if (!strcasecmp(word, "update")) {
23356                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
23357             } else if (!strcasecmp(word, "nonat")) {
23358                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
23359                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
23360             } else {
23361                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
23362             }
23363          }
23364       }
23365    } else if (!strcasecmp(v->name, "insecure")) {
23366       ast_set_flag(&mask[0], SIP_INSECURE);
23367       ast_clear_flag(&flags[0], SIP_INSECURE);
23368       set_insecure_flags(&flags[0], v->value, v->lineno);   
23369    } else if (!strcasecmp(v->name, "progressinband")) {
23370       ast_set_flag(&mask[0], SIP_PROG_INBAND);
23371       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
23372       if (ast_true(v->value))
23373          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
23374       else if (strcasecmp(v->value, "never"))
23375          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
23376    } else if (!strcasecmp(v->name, "promiscredir")) {
23377       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
23378       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
23379    } else if (!strcasecmp(v->name, "videosupport")) {
23380       if (!strcasecmp(v->value, "always")) {
23381          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23382          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23383       } else {
23384          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
23385          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
23386       }
23387    } else if (!strcasecmp(v->name, "textsupport")) {
23388       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
23389       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
23390       res = 1;
23391    } else if (!strcasecmp(v->name, "allowoverlap")) {
23392       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
23393       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
23394    } else if (!strcasecmp(v->name, "allowsubscribe")) {
23395       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
23396       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
23397    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
23398       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
23399       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
23400    } else if (!strcasecmp(v->name, "faxdetect")) {
23401       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
23402       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FAX_DETECT);
23403    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
23404       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
23405       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
23406    } else if (!strcasecmp(v->name, "buggymwi")) {
23407       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
23408       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
23409    } else if (!strcasecmp(v->name, "constantssrc")) {
23410       ast_set_flag(&mask[1], SIP_PAGE2_CONSTANT_SSRC);
23411       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
23412    } else
23413       res = 0;
23414 
23415    return res;
23416 }
23417 
23418 /*! \brief Add SIP domain to list of domains we are responsible for */
23419 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
23420 {
23421    struct domain *d;
23422 
23423    if (ast_strlen_zero(domain)) {
23424       ast_log(LOG_WARNING, "Zero length domain.\n");
23425       return 1;
23426    }
23427 
23428    if (!(d = ast_calloc(1, sizeof(*d))))
23429       return 0;
23430 
23431    ast_copy_string(d->domain, domain, sizeof(d->domain));
23432 
23433    if (!ast_strlen_zero(context))
23434       ast_copy_string(d->context, context, sizeof(d->context));
23435 
23436    d->mode = mode;
23437 
23438    AST_LIST_LOCK(&domain_list);
23439    AST_LIST_INSERT_TAIL(&domain_list, d, list);
23440    AST_LIST_UNLOCK(&domain_list);
23441 
23442    if (sipdebug)  
23443       ast_debug(1, "Added local SIP domain '%s'\n", domain);
23444 
23445    return 1;
23446 }
23447 
23448 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
23449 static int check_sip_domain(const char *domain, char *context, size_t len)
23450 {
23451    struct domain *d;
23452    int result = 0;
23453 
23454    AST_LIST_LOCK(&domain_list);
23455    AST_LIST_TRAVERSE(&domain_list, d, list) {
23456       if (strcasecmp(d->domain, domain))
23457          continue;
23458 
23459       if (len && !ast_strlen_zero(d->context))
23460          ast_copy_string(context, d->context, len);
23461       
23462       result = 1;
23463       break;
23464    }
23465    AST_LIST_UNLOCK(&domain_list);
23466 
23467    return result;
23468 }
23469 
23470 /*! \brief Clear our domain list (at reload) */
23471 static void clear_sip_domains(void)
23472 {
23473    struct domain *d;
23474 
23475    AST_LIST_LOCK(&domain_list);
23476    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
23477       ast_free(d);
23478    AST_LIST_UNLOCK(&domain_list);
23479 }
23480 
23481 
23482 /*! \brief Add realm authentication in list */
23483 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
23484 {
23485    char authcopy[256];
23486    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
23487    struct sip_auth *a, *b, *auth;
23488 
23489    if (ast_strlen_zero(configuration))
23490       return authlist;
23491 
23492    ast_debug(1, "Auth config ::  %s\n", configuration);
23493 
23494    ast_copy_string(authcopy, configuration, sizeof(authcopy));
23495    username = authcopy;
23496 
23497    /* split user[:secret] and relm */
23498    realm = strrchr(username, '@');
23499    if (realm)
23500       *realm++ = '\0';
23501    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
23502       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
23503       return authlist;
23504    }
23505 
23506    /* parse username at ':' for secret, or '#" for md5secret */
23507    if ((secret = strchr(username, ':'))) {
23508       *secret++ = '\0';
23509    } else if ((md5secret = strchr(username, '#'))) {
23510       *md5secret++ = '\0';
23511    }
23512 
23513    if (!(auth = ast_calloc(1, sizeof(*auth))))
23514       return authlist;
23515 
23516    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
23517    ast_copy_string(auth->username, username, sizeof(auth->username));
23518    if (secret)
23519       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
23520    if (md5secret)
23521       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
23522 
23523    /* find the end of the list */
23524    for (b = NULL, a = authlist; a ; b = a, a = a->next)
23525       ;
23526    if (b)
23527       b->next = auth;   /* Add structure add end of list */
23528    else
23529       authlist = auth;
23530 
23531    ast_verb(3, "Added authentication for realm %s\n", realm);
23532 
23533    return authlist;
23534 
23535 }
23536 
23537 /*! \brief Clear realm authentication list (at reload) */
23538 static int clear_realm_authentication(struct sip_auth *authlist)
23539 {
23540    struct sip_auth *a = authlist;
23541    struct sip_auth *b;
23542 
23543    while (a) {
23544       b = a;
23545       a = a->next;
23546       ast_free(b);
23547    }
23548 
23549    return 1;
23550 }
23551 
23552 /*! \brief Find authentication for a specific realm */
23553 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
23554 {
23555    struct sip_auth *a;
23556 
23557    for (a = authlist; a; a = a->next) {
23558       if (!strcasecmp(a->realm, realm))
23559          break;
23560    }
23561 
23562    return a;
23563 }
23564 
23565 /*! \brief
23566  * implement the setvar config line
23567  */
23568 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
23569 {
23570    struct ast_variable *tmpvar = NULL;
23571    char *varname = ast_strdupa(buf), *varval = NULL;
23572    
23573    if ((varval = strchr(varname, '='))) {
23574       *varval++ = '\0';
23575       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
23576          tmpvar->next = list;
23577          list = tmpvar;
23578       }
23579    }
23580    return list;
23581 }
23582 
23583 /*! \brief Set peer defaults before configuring specific configurations */
23584 static void set_peer_defaults(struct sip_peer *peer)
23585 {
23586    if (peer->expire == 0) {
23587       /* Don't reset expire or port time during reload 
23588          if we have an active registration 
23589       */
23590       peer->expire = -1;
23591       peer->pokeexpire = -1;
23592       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
23593       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
23594    }
23595    peer->type = SIP_TYPE_PEER;
23596    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
23597    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
23598    ast_string_field_set(peer, context, sip_cfg.default_context);
23599    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
23600    ast_string_field_set(peer, language, default_language);
23601    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
23602    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
23603    peer->addr.sin_family = AF_INET;
23604    peer->defaddr.sin_family = AF_INET;
23605    peer->capability = global_capability;
23606    peer->maxcallbitrate = default_maxcallbitrate;
23607    peer->rtptimeout = global_rtptimeout;
23608    peer->rtpholdtimeout = global_rtpholdtimeout;
23609    peer->rtpkeepalive = global_rtpkeepalive;
23610    peer->allowtransfer = sip_cfg.allowtransfer;
23611    peer->autoframing = global_autoframing;
23612    peer->t38_maxdatagram = global_t38_maxdatagram;
23613    peer->qualifyfreq = global_qualifyfreq;
23614    if (global_callcounter)
23615       peer->call_limit=INT_MAX;
23616    ast_string_field_set(peer, vmexten, default_vmexten);
23617    ast_string_field_set(peer, secret, "");
23618    ast_string_field_set(peer, remotesecret, "");
23619    ast_string_field_set(peer, md5secret, "");
23620    ast_string_field_set(peer, cid_num, "");
23621    ast_string_field_set(peer, cid_name, "");
23622    ast_string_field_set(peer, fromdomain, "");
23623    ast_string_field_set(peer, fromuser, "");
23624    ast_string_field_set(peer, regexten, "");
23625    peer->callgroup = 0;
23626    peer->pickupgroup = 0;
23627    peer->maxms = default_qualify;
23628    peer->prefs = default_prefs;
23629    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
23630    peer->stimer.st_ref = global_st_refresher;
23631    peer->stimer.st_min_se = global_min_se;
23632    peer->stimer.st_max_se = global_max_se;
23633    peer->timer_t1 = global_t1;
23634    peer->timer_b = global_timer_b;
23635    clear_peer_mailboxes(peer);
23636 }
23637 
23638 /*! \brief Create temporary peer (used in autocreatepeer mode) */
23639 static struct sip_peer *temp_peer(const char *name)
23640 {
23641    struct sip_peer *peer;
23642 
23643    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23644       return NULL;
23645 
23646    if (ast_string_field_init(peer, 512)) {
23647       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23648       return NULL;
23649    }
23650 
23651    ast_atomic_fetchadd_int(&apeerobjs, 1);
23652    set_peer_defaults(peer);
23653 
23654    ast_copy_string(peer->name, name, sizeof(peer->name));
23655 
23656    peer->selfdestruct = TRUE;
23657    peer->host_dynamic = TRUE;
23658    peer->prefs = default_prefs;
23659    reg_source_db(peer);
23660 
23661    return peer;
23662 }
23663 
23664 /*! \todo document this function */
23665 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
23666 {
23667    char *next, *mbox, *context;
23668 
23669    next = ast_strdupa(value);
23670 
23671    while ((mbox = context = strsep(&next, ","))) {
23672       struct sip_mailbox *mailbox;
23673 
23674       if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
23675          continue;
23676 
23677       strsep(&context, "@");
23678       if (ast_strlen_zero(mbox)) {
23679          ast_free(mailbox);
23680          continue;
23681       }
23682       mailbox->mailbox = ast_strdup(mbox);
23683       mailbox->context = ast_strdup(context);
23684 
23685       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
23686    }
23687 }
23688 
23689 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
23690 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
23691 {
23692    struct sip_peer *peer = NULL;
23693    struct ast_ha *oldha = NULL;
23694    int found = 0;
23695    int firstpass = 1;
23696    uint16_t port = 0;
23697    int format = 0;      /* Ama flags */
23698    time_t regseconds = 0;
23699    struct ast_flags peerflags[2] = {{(0)}};
23700    struct ast_flags mask[2] = {{(0)}};
23701    char callback[256] = "";
23702    struct sip_peer tmp_peer;
23703    const char *srvlookup = NULL;
23704    static int deprecation_warning = 1;
23705    int alt_fullcontact = alt ? 1 : 0;
23706    struct ast_str *fullcontact = ast_str_alloca(512);
23707 
23708    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23709       /* Note we do NOT use find_peer here, to avoid realtime recursion */
23710       /* We also use a case-sensitive comparison (unlike find_peer) so
23711          that case changes made to the peer name will be properly handled
23712          during reload
23713       */
23714       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
23715       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
23716    }
23717 
23718    if (peer) {
23719       /* Already in the list, remove it and it will be added back (or FREE'd)  */
23720       found++;
23721       if (!(peer->the_mark))
23722          firstpass = 0;
23723    } else {
23724       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
23725          return NULL;
23726 
23727       if (ast_string_field_init(peer, 512)) {
23728          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
23729          return NULL;
23730       }
23731 
23732       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
23733          ast_atomic_fetchadd_int(&rpeerobjs, 1);
23734          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
23735       } else
23736          ast_atomic_fetchadd_int(&speerobjs, 1);
23737    }
23738 
23739    /* Note that our peer HAS had its reference count increased */
23740    if (firstpass) {
23741       peer->lastmsgssent = -1;
23742       oldha = peer->ha;
23743       peer->ha = NULL;
23744       set_peer_defaults(peer);   /* Set peer defaults */
23745       peer->type = 0;
23746    }
23747    if (!found && name)
23748       ast_copy_string(peer->name, name, sizeof(peer->name));
23749 
23750    /* If we have channel variables, remove them (reload) */
23751    if (peer->chanvars) {
23752       ast_variables_destroy(peer->chanvars);
23753       peer->chanvars = NULL;
23754       /* XXX should unregister ? */
23755    }
23756 
23757    if (found)
23758       peer->portinuri = 0;
23759 
23760    /* If we have realm authentication information, remove them (reload) */
23761    clear_realm_authentication(peer->auth);
23762    peer->auth = NULL;
23763    peer->default_outbound_transport = 0;
23764    peer->transports = 0;
23765 
23766    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
23767       if (!devstate_only) {
23768          if (handle_common_options(&peerflags[0], &mask[0], v)) {
23769             continue;
23770          }
23771          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
23772             continue;
23773          }
23774          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
23775             char *val = ast_strdupa(v->value);
23776             char *trans;
23777 
23778             while ((trans = strsep(&val, ","))) {
23779                trans = ast_skip_blanks(trans);
23780 
23781                if (!strncasecmp(trans, "udp", 3)) {
23782                   peer->transports |= SIP_TRANSPORT_UDP;
23783                } else if (!strncasecmp(trans, "tcp", 3)) {
23784                   peer->transports |= SIP_TRANSPORT_TCP;
23785                } else if (!strncasecmp(trans, "tls", 3)) {
23786                   peer->transports |= SIP_TRANSPORT_TLS;
23787                } else {
23788                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
23789                }
23790 
23791                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
23792                   peer->default_outbound_transport = peer->transports;
23793                }
23794             }
23795          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
23796             ast_get_time_t(v->value, &regseconds, 0, NULL);
23797          } else if (realtime && !strcasecmp(v->name, "name")) {
23798             ast_copy_string(peer->name, v->value, sizeof(peer->name));
23799          } else if (!strcasecmp(v->name, "type")) {
23800             if (!strcasecmp(v->value, "peer")) {
23801                peer->type |= SIP_TYPE_PEER;
23802             } else if (!strcasecmp(v->value, "user")) {
23803                peer->type |= SIP_TYPE_USER;
23804             } else if (!strcasecmp(v->value, "friend")) {
23805                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23806             }
23807          } else if (!strcasecmp(v->name, "remotesecret")) {
23808             ast_string_field_set(peer, remotesecret, v->value);
23809          } else if (!strcasecmp(v->name, "secret")) {
23810             ast_string_field_set(peer, secret, v->value);
23811          } else if (!strcasecmp(v->name, "md5secret")) {
23812             ast_string_field_set(peer, md5secret, v->value);
23813          } else if (!strcasecmp(v->name, "auth")) {
23814             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
23815          } else if (!strcasecmp(v->name, "callerid")) {
23816             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
23817 
23818             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
23819             ast_string_field_set(peer, cid_name, cid_name);
23820             ast_string_field_set(peer, cid_num, cid_num);
23821          } else if (!strcasecmp(v->name, "fullname")) {
23822             ast_string_field_set(peer, cid_name, v->value);
23823          } else if (!strcasecmp(v->name, "trunkname")) {
23824             /* This is actually for a trunk, so we don't want to override callerid */
23825             ast_string_field_set(peer, cid_name, "");
23826          } else if (!strcasecmp(v->name, "cid_number")) {
23827             ast_string_field_set(peer, cid_num, v->value);
23828          } else if (!strcasecmp(v->name, "context")) {
23829             ast_string_field_set(peer, context, v->value);
23830          } else if (!strcasecmp(v->name, "subscribecontext")) {
23831             ast_string_field_set(peer, subscribecontext, v->value);
23832          } else if (!strcasecmp(v->name, "fromdomain")) {
23833             ast_string_field_set(peer, fromdomain, v->value);
23834          } else if (!strcasecmp(v->name, "usereqphone")) {
23835             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
23836          } else if (!strcasecmp(v->name, "fromuser")) {
23837             ast_string_field_set(peer, fromuser, v->value);
23838          } else if (!strcasecmp(v->name, "outboundproxy")) {
23839             char *port, *next, *force, *proxyname;
23840             int forceopt = FALSE;
23841             /* Set peer channel variable */
23842             next = proxyname = ast_strdupa(v->value);
23843             if ((port = strchr(proxyname, ':'))) {
23844                *port++ = '\0';
23845                next = port;
23846             }
23847             if ((force = strchr(next, ','))) {
23848                *force++ = '\0';
23849                forceopt = strcmp(force, "force");
23850             }
23851             /* Allocate proxy object */
23852             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
23853          } else if (!strcasecmp(v->name, "host")) {
23854             if (!strcasecmp(v->value, "dynamic")) {
23855                /* They'll register with us */
23856                if (!found || !peer->host_dynamic) {
23857                   /* Initialize stuff if this is a new peer, or if it used to
23858                    * not be dynamic before the reload. */
23859                   memset(&peer->addr.sin_addr, 0, 4);
23860                   peer->addr.sin_port = 0;
23861                }
23862                peer->host_dynamic = TRUE;
23863             } else {
23864                /* Non-dynamic.  Make sure we become that way if we're not */
23865                AST_SCHED_DEL_UNREF(sched, peer->expire,
23866                      unref_peer(peer, "removing register expire ref"));
23867                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
23868                peer->addr.sin_port = 0;
23869                peer->host_dynamic = FALSE;
23870                srvlookup = v->value;
23871                if (global_dynamic_exclude_static) {
23872                   int err = 0;
23873                   global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
23874                   if (err) {
23875                      ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23876                   }
23877                }
23878             }
23879          } else if (!strcasecmp(v->name, "defaultip")) {
23880             if (ast_get_ip(&peer->defaddr, v->value)) {
23881                unref_peer(peer, "unref_peer: from build_peer defaultip");
23882                return NULL;
23883             }
23884          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
23885             int ha_error = 0;
23886             peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
23887             if (ha_error) {
23888                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23889             }
23890          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
23891             int ha_error = 0;
23892             peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
23893             if (ha_error) {
23894                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23895             }
23896          } else if (!strcasecmp(v->name, "port")) {
23897             peer->portinuri = 1;
23898             if (!(port = port_str2int(v->value, 0))) {
23899                if (realtime) {
23900                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
23901                   peer->portinuri = 0;
23902                } else {
23903                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
23904                }
23905             }
23906          } else if (!strcasecmp(v->name, "callingpres")) {
23907             peer->callingpres = ast_parse_caller_presentation(v->value);
23908             if (peer->callingpres == -1) {
23909                peer->callingpres = atoi(v->value);
23910             }
23911          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
23912             ast_string_field_set(peer, username, v->value);
23913             if (!strcasecmp(v->name, "username")) {
23914                if (deprecation_warning) {
23915                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
23916                   deprecation_warning = 0;
23917                }
23918                peer->deprecated_username = 1;
23919             }
23920          } else if (!strcasecmp(v->name, "language")) {
23921             ast_string_field_set(peer, language, v->value);
23922          } else if (!strcasecmp(v->name, "regexten")) {
23923             ast_string_field_set(peer, regexten, v->value);
23924          } else if (!strcasecmp(v->name, "callbackextension")) {
23925             ast_copy_string(callback, v->value, sizeof(callback));
23926          } else if (!strcasecmp(v->name, "amaflags")) {
23927             format = ast_cdr_amaflags2int(v->value);
23928             if (format < 0) {
23929                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
23930             } else {
23931                peer->amaflags = format;
23932             }
23933          } else if (!strcasecmp(v->name, "accountcode")) {
23934             ast_string_field_set(peer, accountcode, v->value);
23935          } else if (!strcasecmp(v->name, "mohinterpret")) {
23936             ast_string_field_set(peer, mohinterpret, v->value);
23937          } else if (!strcasecmp(v->name, "mohsuggest")) {
23938             ast_string_field_set(peer, mohsuggest, v->value);
23939          } else if (!strcasecmp(v->name, "parkinglot")) {
23940             ast_string_field_set(peer, parkinglot, v->value);
23941          } else if (!strcasecmp(v->name, "mailbox")) {
23942             add_peer_mailboxes(peer, v->value);
23943          } else if (!strcasecmp(v->name, "hasvoicemail")) {
23944             /* People expect that if 'hasvoicemail' is set, that the mailbox will
23945              * be also set, even if not explicitly specified. */
23946             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
23947                add_peer_mailboxes(peer, name);
23948             }
23949          } else if (!strcasecmp(v->name, "subscribemwi")) {
23950             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
23951          } else if (!strcasecmp(v->name, "vmexten")) {
23952             ast_string_field_set(peer, vmexten, v->value);
23953          } else if (!strcasecmp(v->name, "callgroup")) {
23954             peer->callgroup = ast_get_group(v->value);
23955          } else if (!strcasecmp(v->name, "allowtransfer")) {
23956             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
23957          } else if (!strcasecmp(v->name, "pickupgroup")) {
23958             peer->pickupgroup = ast_get_group(v->value);
23959          } else if (!strcasecmp(v->name, "allow")) {
23960             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
23961             if (error) {
23962                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23963             }
23964          } else if (!strcasecmp(v->name, "disallow")) {
23965             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
23966             if (error) {
23967                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23968             }
23969          } else if (!strcasecmp(v->name, "registertrying")) {
23970             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
23971          } else if (!strcasecmp(v->name, "autoframing")) {
23972             peer->autoframing = ast_true(v->value);
23973          } else if (!strcasecmp(v->name, "rtptimeout")) {
23974             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
23975                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
23976                peer->rtptimeout = global_rtptimeout;
23977             }
23978          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
23979             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
23980                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
23981                peer->rtpholdtimeout = global_rtpholdtimeout;
23982             }
23983          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
23984             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
23985                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
23986                peer->rtpkeepalive = global_rtpkeepalive;
23987             }
23988          } else if (!strcasecmp(v->name, "timert1")) {
23989             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
23990                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
23991                peer->timer_t1 = global_t1;
23992             }
23993             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
23994              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
23995             if (peer->timer_b < peer->timer_t1 * 64) {
23996                peer->timer_b = peer->timer_t1 * 64;
23997             }
23998          } else if (!strcasecmp(v->name, "timerb")) {
23999             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
24000                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
24001                peer->timer_b = global_timer_b;
24002             }
24003             if (peer->timer_b < peer->timer_t1 * 64) {
24004                static int warning = 0;
24005                if (warning++ % 20 == 0) {
24006                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
24007                }
24008             }
24009          } else if (!strcasecmp(v->name, "setvar")) {
24010             peer->chanvars = add_var(v->value, peer->chanvars);
24011          } else if (!strcasecmp(v->name, "qualifyfreq")) {
24012             int i;
24013             if (sscanf(v->value, "%30d", &i) == 1) {
24014                peer->qualifyfreq = i * 1000;
24015             } else {
24016                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24017                peer->qualifyfreq = global_qualifyfreq;
24018             }
24019          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24020             peer->maxcallbitrate = atoi(v->value);
24021             if (peer->maxcallbitrate < 0) {
24022                peer->maxcallbitrate = default_maxcallbitrate;
24023             }
24024          } else if (!strcasecmp(v->name, "session-timers")) {
24025             int i = (int) str2stmode(v->value);
24026             if (i < 0) {
24027                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24028                peer->stimer.st_mode_oper = global_st_mode;
24029             } else {
24030                peer->stimer.st_mode_oper = i;
24031             }
24032          } else if (!strcasecmp(v->name, "session-expires")) {
24033             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
24034                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24035                peer->stimer.st_max_se = global_max_se;
24036             }
24037          } else if (!strcasecmp(v->name, "session-minse")) {
24038             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
24039                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24040                peer->stimer.st_min_se = global_min_se;
24041             }
24042             if (peer->stimer.st_min_se < 90) {
24043                ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
24044                peer->stimer.st_min_se = global_min_se;
24045             }
24046          } else if (!strcasecmp(v->name, "session-refresher")) {
24047             int i = (int) str2strefresher(v->value);
24048             if (i < 0) {
24049                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24050                peer->stimer.st_ref = global_st_refresher;
24051             } else {
24052                peer->stimer.st_ref = i;
24053             }
24054          }
24055       }
24056 
24057       /* These apply to devstate lookups */
24058       if (realtime && !strcasecmp(v->name, "lastms")) {
24059          sscanf(v->value, "%30d", &peer->lastms);
24060       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
24061          inet_aton(v->value, &(peer->addr.sin_addr));
24062       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
24063          if (alt_fullcontact && !alt) {
24064             /* Reset, because the alternate also has a fullcontact and we
24065              * do NOT want the field value to be doubled. It might be
24066              * tempting to skip this, but the first table might not have
24067              * fullcontact and since we're here, we know that the alternate
24068              * absolutely does. */
24069             alt_fullcontact = 0;
24070             ast_str_reset(fullcontact);
24071          }
24072          /* Reconstruct field, because realtime separates our value at the ';' */
24073          if (fullcontact->used > 0) {
24074             ast_str_append(&fullcontact, 0, ";%s", v->value);
24075          } else {
24076             ast_str_set(&fullcontact, 0, "%s", v->value);
24077          }
24078       } else if (!strcasecmp(v->name, "qualify")) {
24079          if (!strcasecmp(v->value, "no")) {
24080             peer->maxms = 0;
24081          } else if (!strcasecmp(v->value, "yes")) {
24082             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
24083          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
24084             ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
24085             peer->maxms = 0;
24086          }
24087          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
24088             /* This would otherwise cause a network storm, where the
24089              * qualify response refreshes the peer from the database,
24090              * which in turn causes another qualify to be sent, ad
24091              * infinitum. */
24092             ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime.  Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
24093             peer->maxms = 0;
24094          }
24095       } else if (!strcasecmp(v->name, "callcounter")) {
24096          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
24097       } else if (!strcasecmp(v->name, "call-limit")) {
24098          peer->call_limit = atoi(v->value);
24099          if (peer->call_limit < 0) {
24100             peer->call_limit = 0;
24101          }
24102       } else if (!strcasecmp(v->name, "busylevel")) {
24103          peer->busy_level = atoi(v->value);
24104          if (peer->busy_level < 0) {
24105             peer->busy_level = 0;
24106          }
24107       }
24108    }
24109 
24110    if (!peer->default_outbound_transport) {
24111       /* Set default set of transports */
24112       peer->transports = default_transports;
24113       /* Set default primary transport */
24114       peer->default_outbound_transport = default_primary_transport;
24115    }
24116 
24117    /* The default transport type set during build_peer should only replace the socket.type when...
24118     * 1. Registration is not present and the socket.type and default transport types are different.
24119     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
24120     * 3. The socket.type is not set yet. */
24121    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
24122       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
24123 
24124       set_socket_transport(&peer->socket, peer->default_outbound_transport);
24125    }
24126 
24127    if (port && !realtime && peer->host_dynamic) {
24128       peer->defaddr.sin_port = htons(port);
24129    } else if (port) {
24130       peer->addr.sin_port = htons(port);
24131    }
24132 
24133    if (ast_str_strlen(fullcontact)) {
24134       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
24135       peer->rt_fromcontact = TRUE;
24136       /* We have a hostname in the fullcontact, but if we don't have an
24137        * address listed on the entry (or if it's 'dynamic'), then we need to
24138        * parse the entry to obtain the IP address, so a dynamic host can be
24139        * contacted immediately after reload (as opposed to waiting for it to
24140        * register once again). But if we have an address for this peer and NAT was
24141        * specified, use that address instead. */
24142       /* XXX May need to revisit the final argument; does the realtime DB store whether
24143        * the original contact was over TLS or not? XXX */
24144       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
24145          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
24146       }
24147    }
24148 
24149    if (srvlookup && peer->dnsmgr == NULL) {
24150       char transport[MAXHOSTNAMELEN];
24151       char _srvlookup[MAXHOSTNAMELEN];
24152       char *params;
24153 
24154       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
24155       if ((params = strchr(_srvlookup, ';'))) {
24156          *params++ = '\0';
24157       }
24158 
24159       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
24160 
24161       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL)) {
24162          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
24163          unref_peer(peer, "getting rid of a peer pointer");
24164          return NULL;
24165       }
24166 
24167       ast_string_field_set(peer, tohost, srvlookup);
24168    }
24169 
24170    if (!peer->addr.sin_port) {
24171       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24172    }
24173    if (!peer->defaddr.sin_port) {
24174       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24175    }
24176    if (!peer->socket.port) {
24177       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
24178    }
24179 
24180    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
24181       time_t nowtime = time(NULL);
24182 
24183       if ((nowtime - regseconds) > 0) {
24184          destroy_association(peer);
24185          memset(&peer->addr, 0, sizeof(peer->addr));
24186          peer->lastms = -1;
24187          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
24188       }
24189    }
24190 
24191    /* Startup regular pokes */
24192    if (!devstate_only && realtime && peer->lastms > 0) {
24193       ref_peer(peer, "schedule qualify");
24194       sip_poke_peer(peer, 0);
24195    }
24196 
24197    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
24198    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
24199    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24200       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
24201    }
24202    if (!found && peer->host_dynamic && !peer->is_realtime) {
24203       reg_source_db(peer);
24204    }
24205 
24206    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
24207     * subscribe to it now. */
24208    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
24209       !AST_LIST_EMPTY(&peer->mailboxes)) {
24210       add_peer_mwi_subs(peer);
24211       /* Send MWI from the event cache only.  This is so we can send initial
24212        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
24213        * way, then we will get events when app_voicemail gets loaded. */
24214       sip_send_mwi_to_peer(peer, NULL, 1);
24215    }
24216 
24217    peer->the_mark = 0;
24218 
24219    ast_free_ha(oldha);
24220    if (!ast_strlen_zero(callback)) { /* build string from peer info */
24221       char *reg_string;
24222       if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, callback) < 0) {
24223          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
24224       } else if (reg_string) {
24225          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
24226          ast_free(reg_string);
24227       }
24228    }
24229    return peer;
24230 }
24231 
24232 static int peer_markall_func(void *device, void *arg, int flags)
24233 {
24234    struct sip_peer *peer = device;
24235    peer->the_mark = 1;
24236    return 0;
24237 }
24238 
24239 /*! \brief Re-read SIP.conf config file
24240 \note This function reloads all config data, except for
24241    active peers (with registrations). They will only
24242    change configuration data at restart, not at reload.
24243    SIP debug and recordhistory state will not change
24244  */
24245 static int reload_config(enum channelreloadreason reason)
24246 {
24247    struct ast_config *cfg, *ucfg;
24248    struct ast_variable *v;
24249    struct sip_peer *peer;
24250    char *cat, *stringp, *context, *oldregcontext;
24251    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
24252    struct ast_flags dummy[2];
24253    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
24254    int auto_sip_domains = FALSE;
24255    struct sockaddr_in old_bindaddr = bindaddr;
24256    int registry_count = 0, peer_count = 0;
24257    time_t run_start, run_end;
24258    
24259    run_start = time(0);
24260    ast_unload_realtime("sipregs");     
24261    ast_unload_realtime("sippeers");
24262    cfg = ast_config_load(config, config_flags);
24263 
24264    /* We *must* have a config file otherwise stop immediately */
24265    if (!cfg) {
24266       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
24267       return -1;
24268    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
24269       ucfg = ast_config_load("users.conf", config_flags);
24270       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
24271          return 1;
24272       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
24273          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24274          return 1;
24275       }
24276       /* Must reread both files, because one changed */
24277       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24278       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
24279          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24280          ast_config_destroy(ucfg);
24281          return 1;
24282       }
24283    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
24284       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
24285       return 1;
24286    } else {
24287       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
24288       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
24289          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
24290          ast_config_destroy(cfg);
24291          return 1;
24292       }
24293    }
24294 
24295    /* Initialize tcp sockets */
24296    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
24297    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
24298 
24299    ast_free_ha(global_contact_ha);
24300    global_contact_ha = NULL;
24301 
24302    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
24303 
24304    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
24305    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
24306 
24307    if (reason != CHANNEL_MODULE_LOAD) {
24308       ast_debug(4, "--------------- SIP reload started\n");
24309 
24310       clear_realm_authentication(authl);
24311       clear_sip_domains();
24312       authl = NULL;
24313 
24314       /* First, destroy all outstanding registry calls */
24315       /* This is needed, since otherwise active registry entries will not be destroyed */
24316       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
24317 
24318             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
24319             if (iterator->call) {
24320                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
24321                /* This will also remove references to the registry */
24322                dialog_unlink_all(iterator->call, TRUE, TRUE);
24323                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
24324             }
24325             if (iterator->expire > -1) {
24326                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
24327             }
24328             if (iterator->timeout > -1) {
24329                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
24330             }
24331             ASTOBJ_UNLOCK(iterator);
24332             
24333       } while(0));
24334 
24335       /* Then, actually destroy users and registry */
24336       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24337       ast_debug(4, "--------------- Done destroying registry list\n");
24338       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
24339    }
24340    
24341    /* Reset certificate handling for TLS sessions */
24342    if (reason != CHANNEL_MODULE_LOAD) {
24343       ast_free(default_tls_cfg.certfile);
24344       ast_free(default_tls_cfg.cipher);
24345       ast_free(default_tls_cfg.cafile);
24346       ast_free(default_tls_cfg.capath);
24347    }
24348    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
24349    default_tls_cfg.cipher = ast_strdup("");
24350    default_tls_cfg.cafile = ast_strdup("");
24351    default_tls_cfg.capath = ast_strdup("");
24352 
24353    
24354    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
24355    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
24356    oldregcontext = oldcontexts;
24357 
24358    /* Clear all flags before setting default values */
24359    /* Preserve debugging settings for console */
24360    sipdebug &= sip_debug_console;
24361    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
24362    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
24363 
24364    /* Reset IP addresses  */
24365    memset(&bindaddr, 0, sizeof(bindaddr));
24366    memset(&stunaddr, 0, sizeof(stunaddr));
24367    memset(&internip, 0, sizeof(internip));
24368 
24369    /* Free memory for local network address mask */
24370    ast_free_ha(localaddr);
24371    memset(&localaddr, 0, sizeof(localaddr));
24372    memset(&externip, 0, sizeof(externip));
24373    memset(&default_prefs, 0 , sizeof(default_prefs));
24374    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
24375    sip_cfg.outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
24376    sip_cfg.outboundproxy.ip.sin_family = AF_INET;  /*!< Type of address: IPv4 */
24377    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
24378    default_transports = 0;          /*!< Reset default transport to zero here, default value later on */
24379    default_primary_transport = 0;         /*!< Reset default primary transport to zero here, default value later on */
24380    ourport_tcp = STANDARD_SIP_PORT;
24381    ourport_tls = STANDARD_TLS_PORT;
24382    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
24383    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
24384    global_tos_sip = DEFAULT_TOS_SIP;
24385    global_tos_audio = DEFAULT_TOS_AUDIO;
24386    global_tos_video = DEFAULT_TOS_VIDEO;
24387    global_tos_text = DEFAULT_TOS_TEXT;
24388    global_cos_sip = DEFAULT_COS_SIP;
24389    global_cos_audio = DEFAULT_COS_AUDIO;
24390    global_cos_video = DEFAULT_COS_VIDEO;
24391    global_cos_text = DEFAULT_COS_TEXT;
24392 
24393    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
24394    externexpire = 0;       /* Expiration for DNS re-issuing */
24395    externrefresh = 10;
24396 
24397    /* Reset channel settings to default before re-configuring */
24398    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
24399    global_regcontext[0] = '\0';
24400    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
24401    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
24402    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
24403    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
24404    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
24405    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
24406    sip_cfg.allowsubscribe = FALSE;
24407    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
24408    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
24409    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
24410    global_prematuremediafilter = TRUE;
24411    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
24412    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
24413    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
24414    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
24415    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24416    global_regattempts_max = 0;
24417    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
24418    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
24419    global_autoframing = 0;
24420    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
24421    global_callcounter = DEFAULT_CALLCOUNTER;
24422    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
24423    global_rtptimeout = 0;
24424    global_rtpholdtimeout = 0;
24425    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24426    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
24427    sip_cfg.rtautoclear = 120;
24428    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
24429    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
24430    sip_cfg.peer_rtupdate = TRUE;
24431    global_dynamic_exclude_static = 0;  /* Exclude static peers */
24432 
24433    /* Session-Timers */
24434    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
24435    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24436    global_min_se  = DEFAULT_MIN_SE;
24437    global_max_se  = DEFAULT_MAX_SE;
24438 
24439    /* Peer poking settings */
24440    global_qualify_gap = DEFAULT_QUALIFY_GAP;
24441    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24442 
24443    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
24444    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
24445    sip_cfg.default_subscribecontext[0] = '\0';
24446    default_language[0] = '\0';
24447    default_fromdomain[0] = '\0';
24448    default_qualify = DEFAULT_QUALIFY;
24449    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24450    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
24451    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
24452    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
24453    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
24454    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
24455    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);        /*!< Allow re-invites */
24456 
24457    /* Debugging settings, always default to off */
24458    dumphistory = FALSE;
24459    recordhistory = FALSE;
24460    sipdebug &= ~sip_debug_config;
24461 
24462    /* Misc settings for the channel */
24463    global_relaxdtmf = FALSE;
24464    sip_cfg.callevents = DEFAULT_CALLEVENTS;
24465    global_authfailureevents = FALSE;
24466    global_t1 = DEFAULT_TIMER_T1;
24467    global_timer_b = 64 * DEFAULT_TIMER_T1;
24468    global_t1min = DEFAULT_T1MIN;
24469    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24470    global_t38_maxdatagram = -1;
24471    global_shrinkcallerid = 1;
24472 
24473    sip_cfg.matchexterniplocally = DEFAULT_MATCHEXTERNIPLOCALLY;
24474 
24475    /* Copy the default jb config over global_jbconf */
24476    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
24477 
24478    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
24479    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
24480    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
24481    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
24482 
24483 
24484    /* Read the [general] config section of sip.conf (or from realtime config) */
24485    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
24486       if (handle_common_options(&global_flags[0], &dummy[0], v))
24487          continue;
24488       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
24489          continue;
24490       }
24491       /* handle jb conf */
24492       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
24493          continue;
24494 
24495       if (!strcasecmp(v->name, "context")) {
24496          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
24497       } else if (!strcasecmp(v->name, "subscribecontext")) {
24498          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
24499       } else if (!strcasecmp(v->name, "callcounter")) {
24500          global_callcounter = ast_true(v->value) ? 1 : 0;
24501       } else if (!strcasecmp(v->name, "allowguest")) {
24502          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
24503       } else if (!strcasecmp(v->name, "realm")) {
24504          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
24505       } else if (!strcasecmp(v->name, "useragent")) {
24506          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
24507          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
24508       } else if (!strcasecmp(v->name, "sdpsession")) {
24509          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
24510       } else if (!strcasecmp(v->name, "sdpowner")) {
24511          /* Field cannot contain spaces */
24512          if (!strstr(v->value, " "))
24513             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
24514          else
24515             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
24516       } else if (!strcasecmp(v->name, "allowtransfer")) {
24517          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
24518       } else if (!strcasecmp(v->name, "rtcachefriends")) {
24519          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
24520       } else if (!strcasecmp(v->name, "rtsavesysname")) {
24521          sip_cfg.rtsave_sysname = ast_true(v->value);
24522       } else if (!strcasecmp(v->name, "rtupdate")) {
24523          sip_cfg.peer_rtupdate = ast_true(v->value);
24524       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
24525          sip_cfg.ignore_regexpire = ast_true(v->value);
24526       } else if (!strcasecmp(v->name, "timert1")) {
24527          /* Defaults to 500ms, but RFC 3261 states that it is recommended
24528           * for the value to be set higher, though a lower value is only
24529           * allowed on private networks unconnected to the Internet. */
24530          global_t1 = atoi(v->value);
24531          /* Note that timer B is dependent on the value of T1 */
24532          global_timer_b = global_t1 * 64;
24533       } else if (!strcasecmp(v->name, "t1min")) {
24534          global_t1min = atoi(v->value);
24535       } else if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
24536          char *val = ast_strdupa(v->value);
24537          char *trans;
24538 
24539          while ((trans = strsep(&val, ","))) {
24540             trans = ast_skip_blanks(trans);
24541 
24542             if (!strncasecmp(trans, "udp", 3)) 
24543                default_transports |= SIP_TRANSPORT_UDP;
24544             else if (!strncasecmp(trans, "tcp", 3))
24545                default_transports |= SIP_TRANSPORT_TCP;
24546             else if (!strncasecmp(trans, "tls", 3))
24547                default_transports |= SIP_TRANSPORT_TLS;
24548             else
24549                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
24550             if (default_primary_transport == 0) {
24551                default_primary_transport = default_transports;
24552             }
24553          }
24554       } else if (!strcasecmp(v->name, "tcpenable")) {
24555          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
24556          ast_debug(2, "Enabling TCP socket for listening\n");
24557       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
24558          int family = sip_tcp_desc.local_address.sin_family;
24559          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
24560             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24561          sip_tcp_desc.local_address.sin_family = family;
24562          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
24563       } else if (!strcasecmp(v->name, "tlsenable")) {
24564          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
24565          sip_tls_desc.local_address.sin_family = AF_INET;
24566       } else if (!strcasecmp(v->name, "tlscertfile")) {
24567          ast_free(default_tls_cfg.certfile);
24568          default_tls_cfg.certfile = ast_strdup(v->value);
24569       } else if (!strcasecmp(v->name, "tlscipher")) {
24570          ast_free(default_tls_cfg.cipher);
24571          default_tls_cfg.cipher = ast_strdup(v->value);
24572       } else if (!strcasecmp(v->name, "tlscafile")) {
24573          ast_free(default_tls_cfg.cafile);
24574          default_tls_cfg.cafile = ast_strdup(v->value);
24575       } else if (!strcasecmp(v->name, "tlscapath")) {
24576          ast_free(default_tls_cfg.capath);
24577          default_tls_cfg.capath = ast_strdup(v->value);
24578       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
24579          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
24580       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
24581          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
24582       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
24583          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
24584             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
24585       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
24586          global_dynamic_exclude_static = ast_true(v->value);
24587       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
24588          int ha_error = 0;
24589          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
24590          if (ha_error) {
24591             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
24592          }
24593       } else if (!strcasecmp(v->name, "rtautoclear")) {
24594          int i = atoi(v->value);
24595          if (i > 0)
24596             sip_cfg.rtautoclear = i;
24597          else
24598             i = 0;
24599          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
24600       } else if (!strcasecmp(v->name, "usereqphone")) {
24601          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
24602       } else if (!strcasecmp(v->name, "prematuremedia")) {
24603          global_prematuremediafilter = ast_true(v->value);
24604       } else if (!strcasecmp(v->name, "relaxdtmf")) {
24605          global_relaxdtmf = ast_true(v->value);
24606       } else if (!strcasecmp(v->name, "vmexten")) {
24607          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
24608       } else if (!strcasecmp(v->name, "rtptimeout")) {
24609          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
24610             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24611             global_rtptimeout = 0;
24612          }
24613       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
24614          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
24615             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
24616             global_rtpholdtimeout = 0;
24617          }
24618       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
24619          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
24620             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
24621             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
24622          }
24623       } else if (!strcasecmp(v->name, "compactheaders")) {
24624          sip_cfg.compactheaders = ast_true(v->value);
24625       } else if (!strcasecmp(v->name, "notifymimetype")) {
24626          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
24627       } else if (!strcasecmp(v->name, "directrtpsetup")) {
24628          sip_cfg.directrtpsetup = ast_true(v->value);
24629       } else if (!strcasecmp(v->name, "notifyringing")) {
24630          sip_cfg.notifyringing = ast_true(v->value);
24631       } else if (!strcasecmp(v->name, "notifyhold")) {
24632          sip_cfg.notifyhold = ast_true(v->value);
24633       } else if (!strcasecmp(v->name, "notifycid")) {
24634          if (!strcasecmp(v->value, "ignore-context")) {
24635             sip_cfg.notifycid = IGNORE_CONTEXT;
24636          } else {
24637             sip_cfg.notifycid = ast_true(v->value);
24638          }
24639       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
24640          sip_cfg.alwaysauthreject = ast_true(v->value);
24641       } else if (!strcasecmp(v->name, "mohinterpret")) {
24642          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
24643       } else if (!strcasecmp(v->name, "mohsuggest")) {
24644          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
24645       } else if (!strcasecmp(v->name, "language")) {
24646          ast_copy_string(default_language, v->value, sizeof(default_language));
24647       } else if (!strcasecmp(v->name, "regcontext")) {
24648          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
24649          stringp = newcontexts;
24650          /* Let's remove any contexts that are no longer defined in regcontext */
24651          cleanup_stale_contexts(stringp, oldregcontext);
24652          /* Create contexts if they don't exist already */
24653          while ((context = strsep(&stringp, "&"))) {
24654             ast_copy_string(used_context, context, sizeof(used_context));
24655             ast_context_find_or_create(NULL, NULL, context, "SIP");
24656          }
24657          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
24658       } else if (!strcasecmp(v->name, "regextenonqualify")) {
24659          sip_cfg.regextenonqualify = ast_true(v->value);
24660       } else if (!strcasecmp(v->name, "callerid")) {
24661          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
24662       } else if (!strcasecmp(v->name, "fromdomain")) {
24663          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
24664       } else if (!strcasecmp(v->name, "outboundproxy")) {
24665          int portnum;
24666          char *tok, *proxyname;
24667 
24668          if (ast_strlen_zero(v->value)) {
24669             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
24670             continue;
24671          }
24672 
24673          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
24674 
24675          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &sip_cfg.outboundproxy.transport);
24676 
24677          sip_cfg.outboundproxy.ip.sin_port = htons(portnum);
24678    
24679          if ((tok = strtok(NULL, ","))) {
24680             sip_cfg.outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
24681          } else {
24682             sip_cfg.outboundproxy.force = FALSE;
24683          }
24684 
24685          if (ast_strlen_zero(proxyname)) {
24686             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
24687             sip_cfg.outboundproxy.name[0] = '\0';
24688             continue;
24689          }
24690 
24691          ast_copy_string(sip_cfg.outboundproxy.name, proxyname, sizeof(sip_cfg.outboundproxy.name));
24692 
24693          proxy_update(&sip_cfg.outboundproxy);
24694       } else if (!strcasecmp(v->name, "autocreatepeer")) {
24695          sip_cfg.autocreatepeer = ast_true(v->value);
24696       } else if (!strcasecmp(v->name, "match_auth_username")) {
24697          global_match_auth_username = ast_true(v->value);
24698       } else if (!strcasecmp(v->name, "srvlookup")) {
24699          sip_cfg.srvlookup = ast_true(v->value);
24700       } else if (!strcasecmp(v->name, "pedantic")) {
24701          sip_cfg.pedanticsipchecking = ast_true(v->value);
24702       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
24703          max_expiry = atoi(v->value);
24704          if (max_expiry < 1)
24705             max_expiry = DEFAULT_MAX_EXPIRY;
24706       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
24707          min_expiry = atoi(v->value);
24708          if (min_expiry < 1)
24709             min_expiry = DEFAULT_MIN_EXPIRY;
24710       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
24711          default_expiry = atoi(v->value);
24712          if (default_expiry < 1)
24713             default_expiry = DEFAULT_DEFAULT_EXPIRY;
24714       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
24715          mwi_expiry = atoi(v->value);
24716          if (mwi_expiry < 1)
24717             mwi_expiry = DEFAULT_MWI_EXPIRY;
24718       } else if (!strcasecmp(v->name, "sipdebug")) {
24719          if (ast_true(v->value))
24720             sipdebug |= sip_debug_config;
24721       } else if (!strcasecmp(v->name, "dumphistory")) {
24722          dumphistory = ast_true(v->value);
24723       } else if (!strcasecmp(v->name, "recordhistory")) {
24724          recordhistory = ast_true(v->value);
24725       } else if (!strcasecmp(v->name, "registertimeout")) {
24726          global_reg_timeout = atoi(v->value);
24727          if (global_reg_timeout < 1)
24728             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
24729       } else if (!strcasecmp(v->name, "registerattempts")) {
24730          global_regattempts_max = atoi(v->value);
24731       } else if (!strcasecmp(v->name, "stunaddr")) {
24732          stunaddr.sin_port = htons(3478);
24733          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
24734             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
24735          externexpire = time(NULL);
24736       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
24737          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
24738             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
24739       } else if (!strcasecmp(v->name, "localnet")) {
24740          struct ast_ha *na;
24741          int ha_error = 0;
24742 
24743          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
24744             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
24745          else
24746             localaddr = na;
24747          if (ha_error)
24748             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
24749       } else if (!strcasecmp(v->name, "externip")) {
24750          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
24751             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
24752          externexpire = 0;
24753          /* If no port was specified use the value of bindport */
24754          if (!externip.sin_port)
24755             externip.sin_port = bindaddr.sin_port;
24756       } else if (!strcasecmp(v->name, "externhost")) {
24757          ast_copy_string(externhost, v->value, sizeof(externhost));
24758          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
24759             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
24760          externexpire = time(NULL);
24761          /* If no port was specified use the value of bindport */
24762          if (!externip.sin_port)
24763             externip.sin_port = bindaddr.sin_port;
24764       } else if (!strcasecmp(v->name, "externrefresh")) {
24765          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
24766             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
24767             externrefresh = 10;
24768          }
24769       } else if (!strcasecmp(v->name, "allow")) {
24770          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
24771          if (error)
24772             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24773       } else if (!strcasecmp(v->name, "disallow")) {
24774          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
24775          if (error)
24776             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
24777       } else if (!strcasecmp(v->name, "autoframing")) {
24778          global_autoframing = ast_true(v->value);
24779       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
24780          sip_cfg.allow_external_domains = ast_true(v->value);
24781       } else if (!strcasecmp(v->name, "autodomain")) {
24782          auto_sip_domains = ast_true(v->value);
24783       } else if (!strcasecmp(v->name, "domain")) {
24784          char *domain = ast_strdupa(v->value);
24785          char *cntx = strchr(domain, ',');
24786 
24787          if (cntx)
24788             *cntx++ = '\0';
24789 
24790          if (ast_strlen_zero(cntx))
24791             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
24792          if (ast_strlen_zero(domain))
24793             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
24794          else
24795             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
24796       } else if (!strcasecmp(v->name, "register")) {
24797          if (sip_register(v->value, v->lineno) == 0)
24798             registry_count++;
24799       } else if (!strcasecmp(v->name, "mwi")) {
24800          sip_subscribe_mwi(v->value, v->lineno);
24801       } else if (!strcasecmp(v->name, "tos_sip")) {
24802          if (ast_str2tos(v->value, &global_tos_sip))
24803             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24804       } else if (!strcasecmp(v->name, "tos_audio")) {
24805          if (ast_str2tos(v->value, &global_tos_audio))
24806             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24807       } else if (!strcasecmp(v->name, "tos_video")) {
24808          if (ast_str2tos(v->value, &global_tos_video))
24809             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
24810       } else if (!strcasecmp(v->name, "tos_text")) {
24811          if (ast_str2tos(v->value, &global_tos_text))
24812             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
24813       } else if (!strcasecmp(v->name, "cos_sip")) {
24814          if (ast_str2cos(v->value, &global_cos_sip))
24815             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
24816       } else if (!strcasecmp(v->name, "cos_audio")) {
24817          if (ast_str2cos(v->value, &global_cos_audio))
24818             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
24819       } else if (!strcasecmp(v->name, "cos_video")) {
24820          if (ast_str2cos(v->value, &global_cos_video))
24821             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
24822       } else if (!strcasecmp(v->name, "cos_text")) {
24823          if (ast_str2cos(v->value, &global_cos_text))
24824             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
24825       } else if (!strcasecmp(v->name, "bindport")) {
24826          int i;
24827          if (sscanf(v->value, "%5d", &i) == 1) {
24828             bindaddr.sin_port = htons(i);
24829          } else {
24830             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
24831          }
24832       } else if (!strcasecmp(v->name, "hash_user")) {
24833          int i;
24834          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24835             hash_user_size = i;
24836          } else {
24837             ast_log(LOG_WARNING, "Invalid hash_user size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24838          }
24839       } else if (!strcasecmp(v->name, "hash_peer")) {
24840          int i;
24841          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24842             hash_peer_size = i;
24843          } else {
24844             ast_log(LOG_WARNING, "Invalid hash_peer size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24845          }
24846       } else if (!strcasecmp(v->name, "hash_dialog")) {
24847          int i;
24848          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
24849             hash_dialog_size = i;
24850          } else {
24851             ast_log(LOG_WARNING, "Invalid hash_dialog size '%s' at line %d of %s -- should be much larger than 2\n", v->value, v->lineno, config);
24852          }
24853       } else if (!strcasecmp(v->name, "qualify")) {
24854          if (!strcasecmp(v->value, "no")) {
24855             default_qualify = 0;
24856          } else if (!strcasecmp(v->value, "yes")) {
24857             default_qualify = DEFAULT_MAXMS;
24858          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
24859             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
24860             default_qualify = 0;
24861          }
24862       } else if (!strcasecmp(v->name, "qualifyfreq")) {
24863          int i;
24864          if (sscanf(v->value, "%30d", &i) == 1)
24865             global_qualifyfreq = i * 1000;
24866          else {
24867             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
24868             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
24869          }
24870       } else if (!strcasecmp(v->name, "callevents")) {
24871          sip_cfg.callevents = ast_true(v->value);
24872       } else if (!strcasecmp(v->name, "authfailureevents")) {
24873          global_authfailureevents = ast_true(v->value);
24874       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
24875          default_maxcallbitrate = atoi(v->value);
24876          if (default_maxcallbitrate < 0)
24877             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
24878       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
24879          sip_cfg.matchexterniplocally = ast_true(v->value);
24880       } else if (!strcasecmp(v->name, "constantssrc")) {
24881          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
24882       } else if (!strcasecmp(v->name, "session-timers")) {
24883          int i = (int) str2stmode(v->value); 
24884          if (i < 0) {
24885             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
24886             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
24887          } else {
24888             global_st_mode = i;
24889          }
24890       } else if (!strcasecmp(v->name, "session-expires")) {
24891          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
24892             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
24893             global_max_se = DEFAULT_MAX_SE;
24894          } 
24895       } else if (!strcasecmp(v->name, "session-minse")) {
24896          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
24897             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
24898             global_min_se = DEFAULT_MIN_SE;
24899          } 
24900          if (global_min_se < 90) {
24901             ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
24902             global_min_se = DEFAULT_MIN_SE;
24903          } 
24904       } else if (!strcasecmp(v->name, "session-refresher")) {
24905          int i = (int) str2strefresher(v->value); 
24906          if (i < 0) {
24907             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
24908             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
24909          } else {
24910             global_st_refresher = i;
24911          }
24912       } else if (!strcasecmp(v->name, "qualifygap")) {
24913          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
24914             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
24915             global_qualify_gap = DEFAULT_QUALIFY_GAP;
24916          }
24917       } else if (!strcasecmp(v->name, "qualifypeers")) {
24918          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
24919             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
24920             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
24921          }
24922       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
24923          if (ast_true(v->value)) {
24924             global_shrinkcallerid = 1;
24925          } else if (ast_false(v->value)) {
24926             global_shrinkcallerid = 0;
24927          } else {
24928             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
24929          }
24930       }
24931    }
24932 
24933    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
24934       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
24935       sip_cfg.allow_external_domains = 1;
24936    }
24937    /* If not configured, set default transports */
24938    if (default_transports == 0) {
24939       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
24940    }
24941    
24942    /* Build list of authentication to various SIP realms, i.e. service providers */
24943    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
24944       /* Format for authentication is auth = username:password@realm */
24945       if (!strcasecmp(v->name, "auth"))
24946          authl = add_realm_authentication(authl, v->value, v->lineno);
24947    }
24948    
24949    if (ucfg) {
24950       struct ast_variable *gen;
24951       int genhassip, genregistersip;
24952       const char *hassip, *registersip;
24953       
24954       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
24955       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
24956       gen = ast_variable_browse(ucfg, "general");
24957       cat = ast_category_browse(ucfg, NULL);
24958       while (cat) {
24959          if (strcasecmp(cat, "general")) {
24960             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
24961             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
24962             if (ast_true(hassip) || (!hassip && genhassip)) {
24963                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
24964                if (peer) {
24965                   /* user.conf entries are always of type friend */
24966                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
24967                   ao2_t_link(peers, peer, "link peer into peer table");
24968                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
24969                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
24970                   }
24971                   
24972                   unref_peer(peer, "unref_peer: from reload_config");
24973                   peer_count++;
24974                }
24975             }
24976             if (ast_true(registersip) || (!registersip && genregistersip)) {
24977                char tmp[256];
24978                const char *host = ast_variable_retrieve(ucfg, cat, "host");
24979                const char *username = ast_variable_retrieve(ucfg, cat, "username");
24980                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
24981                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
24982                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
24983                if (!host)
24984                   host = ast_variable_retrieve(ucfg, "general", "host");
24985                if (!username)
24986                   username = ast_variable_retrieve(ucfg, "general", "username");
24987                if (!secret)
24988                   secret = ast_variable_retrieve(ucfg, "general", "secret");
24989                if (!contact)
24990                   contact = "s";
24991                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
24992                   if (!ast_strlen_zero(secret)) {
24993                      if (!ast_strlen_zero(authuser)) {
24994                         snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
24995                      } else {
24996                         snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
24997                      }
24998                   } else if (!ast_strlen_zero(authuser)) {
24999                      snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
25000                   } else {
25001                      snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
25002                   }
25003                   if (sip_register(tmp, 0) == 0)
25004                      registry_count++;
25005                }
25006             }
25007          }
25008          cat = ast_category_browse(ucfg, cat);
25009       }
25010       ast_config_destroy(ucfg);
25011    }
25012    
25013 
25014    /* Load peers, users and friends */
25015    cat = NULL;
25016    while ( (cat = ast_category_browse(cfg, cat)) ) {
25017       const char *utype;
25018       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
25019          continue;
25020       utype = ast_variable_retrieve(cfg, cat, "type");
25021       if (!utype) {
25022          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
25023          continue;
25024       } else {
25025          if (!strcasecmp(utype, "user")) {
25026             ;
25027          } else if (!strcasecmp(utype, "friend")) {
25028             ;
25029          } else if (!strcasecmp(utype, "peer")) {
25030             ;
25031          } else {
25032             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
25033             continue;
25034          }
25035          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
25036          if (peer) {
25037             ao2_t_link(peers, peer, "link peer into peers table");
25038             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
25039                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
25040             }
25041             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
25042             peer_count++;
25043          }
25044       }
25045    }
25046    
25047    /* Set UDP address and open socket */
25048    bindaddr.sin_family = AF_INET;
25049    internip = bindaddr;
25050    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
25051       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
25052       ast_config_destroy(cfg);
25053       return 0;
25054    }
25055    ast_mutex_lock(&netlock);
25056    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
25057       close(sipsock);
25058       sipsock = -1;
25059    }
25060    if (sipsock < 0) {
25061       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
25062       if (sipsock < 0) {
25063          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
25064          ast_config_destroy(cfg);
25065          return -1;
25066       } else {
25067          /* Allow SIP clients on the same host to access us: */
25068          const int reuseFlag = 1;
25069 
25070          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
25071                (const char*)&reuseFlag,
25072                sizeof reuseFlag);
25073 
25074          ast_enable_packet_fragmentation(sipsock);
25075 
25076          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
25077             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
25078             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
25079             strerror(errno));
25080             close(sipsock);
25081             sipsock = -1;
25082          } else {
25083             ast_verb(2, "SIP Listening on %s:%d\n",
25084                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
25085             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
25086          }
25087       }
25088    }
25089    if (stunaddr.sin_addr.s_addr != 0) {
25090       ast_debug(1, "stun to %s:%d\n",
25091          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
25092       ast_stun_request(sipsock, &stunaddr,
25093          NULL, &externip);
25094       ast_debug(1, "STUN sees us at %s:%d\n", 
25095          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
25096    }
25097    ast_mutex_unlock(&netlock);
25098 
25099    /* Start TCP server */
25100    ast_tcptls_server_start(&sip_tcp_desc);
25101    if (sip_tcp_desc.accept_fd == -1 &&  sip_tcp_desc.local_address.sin_family == AF_INET) {
25102       /* TCP server start failed. Tell the admin */
25103       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
25104       sip_tcp_desc.local_address.sin_family = 0;
25105    } else {
25106       ast_debug(2, "SIP TCP server started\n");
25107    }
25108 
25109    /* Start TLS server if needed */
25110    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
25111 
25112    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
25113       ast_tcptls_server_start(&sip_tls_desc);
25114       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
25115          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
25116          sip_tls_desc.tls_cfg = NULL;
25117       }
25118    } else if (sip_tls_desc.tls_cfg->enabled) {
25119       sip_tls_desc.tls_cfg = NULL;
25120       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
25121    }
25122 
25123 
25124    /* Add default domains - host name, IP address and IP:port
25125     * Only do this if user added any sip domain with "localdomains" 
25126     * In order to *not* break backwards compatibility 
25127     *    Some phones address us at IP only, some with additional port number 
25128     */
25129    if (auto_sip_domains) {
25130       char temp[MAXHOSTNAMELEN];
25131 
25132       /* First our default IP address */
25133       if (bindaddr.sin_addr.s_addr) {
25134          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
25135       } else if (internip.sin_addr.s_addr) {
25136       /* Our internal IP address, if configured */
25137          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25138       } else {
25139          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
25140       }
25141 
25142       /* If TCP is running on a different IP than UDP, then add it too */
25143       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
25144          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25145 
25146       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
25147       if (sip_tls_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tls_desc.local_address) && inaddrcmp(&sip_tcp_desc.local_address, &sip_tls_desc.local_address))
25148          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
25149 
25150       /* Our extern IP address, if configured */
25151       if (externip.sin_addr.s_addr)
25152          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
25153 
25154       /* Extern host name (NAT traversal support) */
25155       if (!ast_strlen_zero(externhost))
25156          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
25157       
25158       /* Our host name */
25159       if (!gethostname(temp, sizeof(temp)))
25160          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
25161    }
25162 
25163    /* Release configuration from memory */
25164    ast_config_destroy(cfg);
25165 
25166    /* Load the list of manual NOTIFY types to support */
25167    if (notify_types)
25168       ast_config_destroy(notify_types);
25169    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
25170       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
25171       notify_types = NULL;
25172    }
25173 
25174    /* Done, tell the manager */
25175    manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
25176    run_end = time(0);
25177    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
25178 
25179    return 0;
25180 }
25181 
25182 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
25183 {
25184    struct sip_pvt *p;
25185    struct ast_udptl *udptl = NULL;
25186    
25187    p = chan->tech_pvt;
25188    if (!p)
25189       return NULL;
25190    
25191    sip_pvt_lock(p);
25192    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25193       udptl = p->udptl;
25194    sip_pvt_unlock(p);
25195    return udptl;
25196 }
25197 
25198 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
25199 {
25200    struct sip_pvt *p;
25201    
25202    p = chan->tech_pvt;
25203    if (!p)
25204       return -1;
25205    sip_pvt_lock(p);
25206    if (udptl)
25207       ast_udptl_get_peer(udptl, &p->udptlredirip);
25208    else
25209       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
25210    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
25211       if (!p->pendinginvite) {
25212          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
25213          transmit_reinvite_with_sdp(p, TRUE, FALSE);
25214       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25215          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s:%d\n", p->callid, ast_inet_ntoa(udptl ? p->udptlredirip.sin_addr : p->ourip.sin_addr), udptl ? ntohs(p->udptlredirip.sin_port) : 0);
25216          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
25217       }
25218    }
25219    /* Reset lastrtprx timer */
25220    p->lastrtprx = p->lastrtptx = time(NULL);
25221    sip_pvt_unlock(p);
25222    return 0;
25223 }
25224 
25225 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
25226 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25227 {
25228    struct sip_pvt *p = NULL;
25229    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25230 
25231    if (!(p = chan->tech_pvt))
25232       return AST_RTP_GET_FAILED;
25233 
25234    sip_pvt_lock(p);
25235    if (!(p->rtp)) {
25236       sip_pvt_unlock(p);
25237       return AST_RTP_GET_FAILED;
25238    }
25239 
25240    *rtp = p->rtp;
25241 
25242    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT))
25243       res = AST_RTP_TRY_PARTIAL;
25244    else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25245       res = AST_RTP_TRY_NATIVE;
25246    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
25247       res = AST_RTP_GET_FAILED;
25248 
25249    sip_pvt_unlock(p);
25250 
25251    return res;
25252 }
25253 
25254 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
25255 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25256 {
25257    struct sip_pvt *p = NULL;
25258    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25259    
25260    if (!(p = chan->tech_pvt))
25261       return AST_RTP_GET_FAILED;
25262 
25263    sip_pvt_lock(p);
25264    if (!(p->vrtp)) {
25265       sip_pvt_unlock(p);
25266       return AST_RTP_GET_FAILED;
25267    }
25268 
25269    *rtp = p->vrtp;
25270 
25271    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25272       res = AST_RTP_TRY_NATIVE;
25273 
25274    sip_pvt_unlock(p);
25275 
25276    return res;
25277 }
25278 
25279 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
25280 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
25281 {
25282    struct sip_pvt *p = NULL;
25283    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
25284    
25285    if (!(p = chan->tech_pvt))
25286       return AST_RTP_GET_FAILED;
25287 
25288    sip_pvt_lock(p);
25289    if (!(p->trtp)) {
25290       sip_pvt_unlock(p);
25291       return AST_RTP_GET_FAILED;
25292    }
25293 
25294    *rtp = p->trtp;
25295 
25296    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA))
25297       res = AST_RTP_TRY_NATIVE;
25298 
25299    sip_pvt_unlock(p);
25300 
25301    return res;
25302 }
25303 
25304 /*! \brief Set the RTP peer for this call */
25305 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, struct ast_rtp *trtp, int codecs, int nat_active)
25306 {
25307    struct sip_pvt *p;
25308    int changed = 0;
25309 
25310    p = chan->tech_pvt;
25311    if (!p) 
25312       return -1;
25313 
25314    /* Disable early RTP bridge  */
25315    if (!ast_bridged_channel(chan) && !sip_cfg.directrtpsetup)  /* We are in early state */
25316       return 0;
25317 
25318    sip_pvt_lock(p);
25319    if (p->alreadygone) {
25320       /* If we're destroyed, don't bother */
25321       sip_pvt_unlock(p);
25322       return 0;
25323    }
25324 
25325    /* if this peer cannot handle reinvites of the media stream to devices
25326       that are known to be behind a NAT, then stop the process now
25327    */
25328         if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
25329                 sip_pvt_unlock(p);
25330                 return 0;
25331         }
25332 
25333    if (rtp) {
25334       changed |= ast_rtp_get_peer(rtp, &p->redirip);
25335    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
25336       memset(&p->redirip, 0, sizeof(p->redirip));
25337       changed = 1;
25338    }
25339    if (vrtp) {
25340       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
25341    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
25342       memset(&p->vredirip, 0, sizeof(p->vredirip));
25343       changed = 1;
25344    }
25345    if (trtp) {
25346       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
25347    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
25348       memset(&p->tredirip, 0, sizeof(p->tredirip));
25349       changed = 1;
25350    }
25351    if (codecs && (p->redircodecs != codecs)) {
25352       p->redircodecs = codecs;
25353       changed = 1;
25354    }
25355    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
25356       if (chan->_state != AST_STATE_UP) { /* We are in early state */
25357          if (p->do_history)
25358             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
25359          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
25360       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
25361          ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
25362          transmit_reinvite_with_sdp(p, FALSE, FALSE);
25363       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
25364          ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_inet_ntoa(rtp ? p->redirip.sin_addr : p->ourip.sin_addr));
25365          /* We have a pending Invite. Send re-invite when we're done with the invite */
25366          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
25367       }
25368    }
25369    /* Reset lastrtprx timer */
25370    p->lastrtprx = p->lastrtptx = time(NULL);
25371    sip_pvt_unlock(p);
25372    return 0;
25373 }
25374 
25375 static char *app_dtmfmode = "SIPDtmfMode";
25376 static char *app_sipaddheader = "SIPAddHeader";
25377 static char *app_sipremoveheader = "SIPRemoveHeader";
25378 
25379 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
25380 static int sip_dtmfmode(struct ast_channel *chan, void *data)
25381 {
25382    struct sip_pvt *p;
25383    char *mode = data;
25384 
25385    if (!data) {
25386       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
25387       return 0;
25388    }
25389    ast_channel_lock(chan);
25390    if (!IS_SIP_TECH(chan->tech)) {
25391       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
25392       ast_channel_unlock(chan);
25393       return 0;
25394    }
25395    p = chan->tech_pvt;
25396    if (!p) {
25397       ast_channel_unlock(chan);
25398       return 0;
25399    }
25400    sip_pvt_lock(p);
25401    if (!strcasecmp(mode, "info")) {
25402       ast_clear_flag(&p->flags[0], SIP_DTMF);
25403       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
25404       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25405    } else if (!strcasecmp(mode, "shortinfo")) {
25406       ast_clear_flag(&p->flags[0], SIP_DTMF);
25407       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
25408       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25409    } else if (!strcasecmp(mode, "rfc2833")) {
25410       ast_clear_flag(&p->flags[0], SIP_DTMF);
25411       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
25412       p->jointnoncodeccapability |= AST_RTP_DTMF;
25413    } else if (!strcasecmp(mode, "inband")) { 
25414       ast_clear_flag(&p->flags[0], SIP_DTMF);
25415       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
25416       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
25417    } else
25418       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
25419    if (p->rtp)
25420       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25421    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
25422       if (!p->dsp) {
25423          p->dsp = ast_dsp_new();
25424          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
25425       }
25426    } else {
25427       if (p->dsp) {
25428          ast_dsp_free(p->dsp);
25429          p->dsp = NULL;
25430       }
25431    }
25432    sip_pvt_unlock(p);
25433    ast_channel_unlock(chan);
25434    return 0;
25435 }
25436 
25437 /*! \brief Add a SIP header to an outbound INVITE */
25438 static int sip_addheader(struct ast_channel *chan, void *data)
25439 {
25440    int no = 0;
25441    int ok = FALSE;
25442    char varbuf[30];
25443    char *inbuf = data, *subbuf;
25444    
25445    if (ast_strlen_zero(inbuf)) {
25446       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
25447       return 0;
25448    }
25449    ast_channel_lock(chan);
25450 
25451    /* Check for headers */
25452    while (!ok && no <= 50) {
25453       no++;
25454       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
25455 
25456       /* Compare without the leading underscores */
25457       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
25458          ok = TRUE;
25459       }
25460    }
25461    if (ok) {
25462       size_t len = strlen(inbuf);
25463       subbuf = alloca(len + 1);
25464       ast_get_encoded_str(inbuf, subbuf, len + 1);
25465       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
25466       if (sipdebug) {
25467          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
25468       }
25469    } else {
25470       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
25471    }
25472    ast_channel_unlock(chan);
25473    return 0;
25474 }
25475 
25476 /*! \brief Remove SIP headers added previously with SipAddHeader application */
25477 static int sip_removeheader(struct ast_channel *chan, void *data)
25478 {
25479    struct ast_var_t *newvariable;
25480    struct varshead *headp;
25481    int removeall = 0;
25482    char *inbuf = (char *) data;
25483 
25484    if (ast_strlen_zero(inbuf)) {
25485       removeall = 1;
25486    }
25487    ast_channel_lock(chan);
25488  
25489    headp=&chan->varshead;
25490    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
25491       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
25492          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
25493             if (sipdebug)
25494                ast_log(LOG_DEBUG,"removing SIP Header \"%s\" as %s\n",
25495                   ast_var_value(newvariable),
25496                   ast_var_name(newvariable));
25497             AST_LIST_REMOVE_CURRENT(entries);
25498             ast_var_delete(newvariable);
25499          }
25500       }
25501    }
25502    AST_LIST_TRAVERSE_SAFE_END;
25503  
25504    ast_channel_unlock(chan);
25505    return 0;
25506 }
25507 
25508 /*! \brief Transfer call before connect with a 302 redirect
25509 \note Called by the transfer() dialplan application through the sip_transfer()
25510    pbx interface function if the call is in ringing state 
25511 \todo Fix this function so that we wait for reply to the REFER and
25512    react to errors, denials or other issues the other end might have.
25513  */
25514 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
25515 {
25516    char *cdest;
25517    char *extension, *host, *port;
25518    char tmp[80];
25519 
25520    cdest = ast_strdupa(dest);
25521    
25522    extension = strsep(&cdest, "@");
25523    host = strsep(&cdest, ":");
25524    port = strsep(&cdest, ":");
25525    if (ast_strlen_zero(extension)) {
25526       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
25527       return 0;
25528    }
25529 
25530    /* we'll issue the redirect message here */
25531    if (!host) {
25532       char *localtmp;
25533 
25534       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
25535       if (ast_strlen_zero(tmp)) {
25536          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
25537          return 0;
25538       }
25539       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
25540          && (localtmp = strchr(localtmp, '@'))) {
25541          char lhost[80], lport[80];
25542 
25543          memset(lhost, 0, sizeof(lhost));
25544          memset(lport, 0, sizeof(lport));
25545          localtmp++;
25546          /* This is okey because lhost and lport are as big as tmp */
25547          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
25548          if (ast_strlen_zero(lhost)) {
25549             ast_log(LOG_ERROR, "Can't find the host address\n");
25550             return 0;
25551          }
25552          host = ast_strdupa(lhost);
25553          if (!ast_strlen_zero(lport)) {
25554             port = ast_strdupa(lport);
25555          }
25556       }
25557    }
25558 
25559    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
25560    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
25561 
25562    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
25563    sip_alreadygone(p);
25564    /* hangup here */
25565    return 0;
25566 }
25567 
25568 /*! \brief Return SIP UA's codec (part of the RTP interface) */
25569 static int sip_get_codec(struct ast_channel *chan)
25570 {
25571    struct sip_pvt *p = chan->tech_pvt;
25572    return p->jointcapability ? p->jointcapability : p->capability;   
25573 }
25574 
25575 /*! \brief Send a poke to all known peers */
25576 static void sip_poke_all_peers(void)
25577 {
25578    int ms = 0, num = 0;
25579    struct ao2_iterator i;
25580    struct sip_peer *peer;
25581 
25582    if (!speerobjs)   /* No peers, just give up */
25583       return;
25584 
25585    i = ao2_iterator_init(peers, 0);
25586    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
25587       ao2_lock(peer);
25588       if (num == global_qualify_peers) {
25589          ms += global_qualify_gap;
25590          num = 0;
25591       } else {
25592          num++;
25593       }
25594       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
25595             unref_peer(_data, "removing poke peer ref"),
25596             unref_peer(peer, "removing poke peer ref"),
25597             ref_peer(peer, "adding poke peer ref"));
25598       ao2_unlock(peer);
25599       unref_peer(peer, "toss iterator peer ptr");
25600    }
25601    ao2_iterator_destroy(&i);
25602 }
25603 
25604 /*! \brief Send all known registrations */
25605 static void sip_send_all_registers(void)
25606 {
25607    int ms;
25608    int regspacing;
25609    if (!regobjs)
25610       return;
25611    regspacing = default_expiry * 1000/regobjs;
25612    if (regspacing > 100)
25613       regspacing = 100;
25614    ms = regspacing;
25615    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
25616       ASTOBJ_WRLOCK(iterator);
25617       ms += regspacing;
25618       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
25619                         registry_unref(_data, "REPLACE sched del decs the refcount"),
25620                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
25621                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
25622       ASTOBJ_UNLOCK(iterator);
25623    } while (0)
25624    );
25625 }
25626 
25627 /*! \brief Send all MWI subscriptions */
25628 static void sip_send_all_mwi_subscriptions(void)
25629 {
25630    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
25631       ASTOBJ_WRLOCK(iterator);
25632       AST_SCHED_DEL(sched, iterator->resub);
25633       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, ASTOBJ_REF(iterator))) < 0) {
25634          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
25635       }
25636       ASTOBJ_UNLOCK(iterator);
25637    } while (0));
25638 }
25639 
25640 /*! \brief Reload module */
25641 static int sip_do_reload(enum channelreloadreason reason)
25642 {
25643    time_t start_poke, end_poke;
25644    
25645    reload_config(reason);
25646    ast_sched_dump(sched);
25647 
25648    start_poke = time(0);
25649    /* Prune peers who still are supposed to be deleted */
25650    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, NULL,
25651          "callback to remove marked peers");
25652    
25653    ast_debug(4, "--------------- Done destroying pruned peers\n");
25654 
25655    /* Send qualify (OPTIONS) to all peers */
25656    sip_poke_all_peers();
25657 
25658    /* Register with all services */
25659    sip_send_all_registers();
25660 
25661    sip_send_all_mwi_subscriptions();
25662 
25663    end_poke = time(0);
25664    
25665    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
25666 
25667    ast_debug(4, "--------------- SIP reload done\n");
25668 
25669    return 0;
25670 }
25671 
25672 /*! \brief Force reload of module from cli */
25673 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
25674 {
25675    
25676    switch (cmd) {
25677    case CLI_INIT:
25678       e->command = "sip reload";
25679       e->usage =
25680          "Usage: sip reload\n"
25681          "       Reloads SIP configuration from sip.conf\n";
25682       return NULL;
25683    case CLI_GENERATE:
25684       return NULL;
25685    }
25686 
25687    ast_mutex_lock(&sip_reload_lock);
25688    if (sip_reloading) 
25689       ast_verbose("Previous SIP reload not yet done\n");
25690    else {
25691       sip_reloading = TRUE;
25692       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
25693    }
25694    ast_mutex_unlock(&sip_reload_lock);
25695    restart_monitor();
25696 
25697    return CLI_SUCCESS;
25698 }
25699 
25700 /*! \brief  Part of Asterisk module interface */
25701 static int reload(void)
25702 {
25703    if (sip_reload(0, 0, NULL))
25704       return 0;
25705    return 1;
25706 }
25707 
25708 /*! \brief SIP Cli commands definition */
25709 static struct ast_cli_entry cli_sip[] = {
25710    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
25711    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
25712    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
25713    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
25714    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
25715    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
25716    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
25717    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
25718    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
25719    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
25720    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
25721    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
25722    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
25723    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
25724    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
25725    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
25726    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
25727    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
25728    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
25729    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
25730    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
25731    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
25732    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
25733 };
25734 
25735 /*! \brief PBX load module - initialization */
25736 static int load_module(void)
25737 {
25738    ast_verbose("SIP channel loading...\n");
25739    /* the fact that ao2_containers can't resize automatically is a major worry! */
25740    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
25741    peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
25742    peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
25743    dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
25744    threadt = ao2_t_container_alloc(hash_dialog_size, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
25745    
25746    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
25747    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
25748 
25749    if (!(sched = sched_context_create())) {
25750       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
25751       return AST_MODULE_LOAD_FAILURE;
25752    }
25753 
25754    if (!(io = io_context_create())) {
25755       ast_log(LOG_ERROR, "Unable to create I/O context\n");
25756       sched_context_destroy(sched);
25757       return AST_MODULE_LOAD_FAILURE;
25758    }
25759 
25760    sip_reloadreason = CHANNEL_MODULE_LOAD;
25761 
25762    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
25763       return AST_MODULE_LOAD_DECLINE;
25764 
25765    /* Prepare the version that does not require DTMF BEGIN frames.
25766     * We need to use tricks such as memcpy and casts because the variable
25767     * has const fields.
25768     */
25769    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
25770    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
25771 
25772    /* Make sure we can register our sip channel type */
25773    if (ast_channel_register(&sip_tech)) {
25774       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
25775       io_context_destroy(io);
25776       sched_context_destroy(sched);
25777       return AST_MODULE_LOAD_FAILURE;
25778    }
25779 
25780    /* Register all CLI functions for SIP */
25781    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
25782 
25783    /* Tell the RTP subdriver that we're here */
25784    ast_rtp_proto_register(&sip_rtp);
25785 
25786    /* Tell the UDPTL subdriver that we're here */
25787    ast_udptl_proto_register(&sip_udptl);
25788 
25789    /* Register dialplan applications */
25790    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
25791    ast_register_application_xml(app_sipaddheader, sip_addheader);
25792    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
25793 
25794    /* Register dialplan functions */
25795    ast_custom_function_register(&sip_header_function);
25796    ast_custom_function_register(&sippeer_function);
25797    ast_custom_function_register(&sipchaninfo_function);
25798    ast_custom_function_register(&checksipdomain_function);
25799 
25800    /* Register manager commands */
25801    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
25802          "List SIP peers (text format)", mandescr_show_peers);
25803    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
25804          "Show SIP peer (text format)", mandescr_show_peer);
25805    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
25806          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
25807    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
25808          "Show SIP registrations (text format)", mandescr_show_registry);
25809    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
25810          "Send a SIP notify", mandescr_sipnotify);
25811    sip_poke_all_peers();   
25812    sip_send_all_registers();
25813    sip_send_all_mwi_subscriptions();
25814 
25815    /* And start the monitor for the first time */
25816    restart_monitor();
25817 
25818    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
25819       "name", RQ_CHAR, 10,
25820       "ipaddr", RQ_CHAR, 15,
25821       "port", RQ_UINTEGER2, 5,
25822       "regseconds", RQ_INTEGER4, 11,
25823       "defaultuser", RQ_CHAR, 10,
25824       "fullcontact", RQ_CHAR, 35,
25825       "regserver", RQ_CHAR, 20,
25826       "useragent", RQ_CHAR, 20,
25827       "lastms", RQ_INTEGER4, 11,
25828       SENTINEL);
25829 
25830    return AST_MODULE_LOAD_SUCCESS;
25831 }
25832 
25833 /*! \brief PBX unload module API */
25834 static int unload_module(void)
25835 {
25836    struct sip_pvt *p;
25837    struct sip_threadinfo *th;
25838    struct ast_context *con;
25839    struct ao2_iterator i;
25840 
25841    ast_sched_dump(sched);
25842    
25843    /* First, take us out of the channel type list */
25844    ast_channel_unregister(&sip_tech);
25845 
25846    /* Unregister dial plan functions */
25847    ast_custom_function_unregister(&sipchaninfo_function);
25848    ast_custom_function_unregister(&sippeer_function);
25849    ast_custom_function_unregister(&sip_header_function);
25850    ast_custom_function_unregister(&checksipdomain_function);
25851 
25852    /* Unregister dial plan applications */
25853    ast_unregister_application(app_dtmfmode);
25854    ast_unregister_application(app_sipaddheader);
25855    ast_unregister_application(app_sipremoveheader);
25856 
25857    /* Unregister CLI commands */
25858    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
25859 
25860    /* Disconnect from the RTP subsystem */
25861    ast_rtp_proto_unregister(&sip_rtp);
25862 
25863    /* Disconnect from UDPTL */
25864    ast_udptl_proto_unregister(&sip_udptl);
25865 
25866    /* Unregister AMI actions */
25867    ast_manager_unregister("SIPpeers");
25868    ast_manager_unregister("SIPshowpeer");
25869    ast_manager_unregister("SIPqualifypeer");
25870    ast_manager_unregister("SIPshowregistry");
25871    ast_manager_unregister("SIPnotify");
25872    
25873    /* Kill TCP/TLS server threads */
25874    if (sip_tcp_desc.master)
25875       ast_tcptls_server_stop(&sip_tcp_desc);
25876    if (sip_tls_desc.master)
25877       ast_tcptls_server_stop(&sip_tls_desc);
25878 
25879    /* Kill all existing TCP/TLS threads */
25880    i = ao2_iterator_init(threadt, 0);
25881    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
25882       pthread_t thread = th->threadid;
25883       th->stop = 1;
25884       pthread_kill(thread, SIGURG);
25885       pthread_join(thread, NULL);
25886       ao2_t_ref(th, -1, "decrement ref from iterator");
25887    }
25888    ao2_iterator_destroy(&i);
25889 
25890    /* Hangup all dialogs if they have an owner */
25891    i = ao2_iterator_init(dialogs, 0);
25892    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
25893       if (p->owner)
25894          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
25895       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
25896    }
25897    ao2_iterator_destroy(&i);
25898 
25899    ast_mutex_lock(&monlock);
25900    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
25901       pthread_cancel(monitor_thread);
25902       pthread_kill(monitor_thread, SIGURG);
25903       pthread_join(monitor_thread, NULL);
25904    }
25905    monitor_thread = AST_PTHREADT_STOP;
25906    ast_mutex_unlock(&monlock);
25907 
25908    /* Destroy all the dialogs and free their memory */
25909    i = ao2_iterator_init(dialogs, 0);
25910    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
25911       dialog_unlink_all(p, TRUE, TRUE);
25912       ao2_t_ref(p, -1, "throw away iterator result"); 
25913    }
25914    ao2_iterator_destroy(&i);
25915 
25916    /* Free memory for local network address mask */
25917    ast_free_ha(localaddr);
25918 
25919    clear_realm_authentication(authl);
25920 
25921 
25922    if (default_tls_cfg.certfile)
25923       ast_free(default_tls_cfg.certfile);
25924    if (default_tls_cfg.cipher)
25925       ast_free(default_tls_cfg.cipher);
25926    if (default_tls_cfg.cafile)
25927       ast_free(default_tls_cfg.cafile);
25928    if (default_tls_cfg.capath)
25929       ast_free(default_tls_cfg.capath);
25930 
25931    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
25932    ASTOBJ_CONTAINER_DESTROY(&regl);
25933    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
25934    ASTOBJ_CONTAINER_DESTROY(&submwil);
25935 
25936    ao2_t_ref(peers, -1, "unref the peers table");
25937    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
25938    ao2_t_ref(dialogs, -1, "unref the dialogs table");
25939    ao2_t_ref(threadt, -1, "unref the thread table");
25940 
25941    clear_sip_domains();
25942    ast_free_ha(global_contact_ha);
25943    close(sipsock);
25944    sched_context_destroy(sched);
25945    con = ast_context_find(used_context);
25946    if (con)
25947       ast_context_destroy(con, "SIP");
25948    ast_unload_realtime("sipregs");
25949    ast_unload_realtime("sippeers");
25950 
25951    return 0;
25952 }
25953 
25954 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
25955       .load = load_module,
25956       .unload = unload_module,
25957       .reload = reload,
25958           );

Generated on Wed May 5 15:18:36 2010 for Asterisk - the Open Source PBX by  doxygen 1.6.1